Re-landing:
[WebKit-https.git] / Source / WebKit2 / UIProcess / WebPageProxy.cpp
1 /*
2  * Copyright (C) 2010, 2011, 2015-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2012 Intel Corporation. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "WebPageProxy.h"
29
30 #include "APIArray.h"
31 #include "APIContextMenuClient.h"
32 #include "APIFindClient.h"
33 #include "APIFindMatchesClient.h"
34 #include "APIFormClient.h"
35 #include "APIFrameInfo.h"
36 #include "APIFullscreenClient.h"
37 #include "APIGeometry.h"
38 #include "APIHistoryClient.h"
39 #include "APIHitTestResult.h"
40 #include "APIIconLoadingClient.h"
41 #include "APILegacyContextHistoryClient.h"
42 #include "APILoaderClient.h"
43 #include "APINavigation.h"
44 #include "APINavigationAction.h"
45 #include "APINavigationClient.h"
46 #include "APINavigationResponse.h"
47 #include "APIOpenPanelParameters.h"
48 #include "APIPageConfiguration.h"
49 #include "APIPolicyClient.h"
50 #include "APISecurityOrigin.h"
51 #include "APIUIClient.h"
52 #include "APIURLRequest.h"
53 #include "AuthenticationChallengeProxy.h"
54 #include "AuthenticationDecisionListener.h"
55 #include "DataReference.h"
56 #include "DownloadProxy.h"
57 #include "DrawingAreaProxy.h"
58 #include "DrawingAreaProxyMessages.h"
59 #include "EventDispatcherMessages.h"
60 #include "LoadParameters.h"
61 #include "Logging.h"
62 #include "NativeWebGestureEvent.h"
63 #include "NativeWebKeyboardEvent.h"
64 #include "NativeWebMouseEvent.h"
65 #include "NativeWebWheelEvent.h"
66 #include "NavigationActionData.h"
67 #include "NetworkProcessMessages.h"
68 #include "NotificationPermissionRequest.h"
69 #include "NotificationPermissionRequestManager.h"
70 #include "PageClient.h"
71 #include "PluginInformation.h"
72 #include "PluginProcessManager.h"
73 #include "PrintInfo.h"
74 #include "TextChecker.h"
75 #include "TextCheckerState.h"
76 #include "UserMediaPermissionRequestProxy.h"
77 #include "WKContextPrivate.h"
78 #include "WebAutomationSession.h"
79 #include "WebBackForwardList.h"
80 #include "WebBackForwardListItem.h"
81 #include "WebCertificateInfo.h"
82 #include "WebContextMenuItem.h"
83 #include "WebContextMenuProxy.h"
84 #include "WebCoreArgumentCoders.h"
85 #include "WebEditCommandProxy.h"
86 #include "WebEvent.h"
87 #include "WebEventConversion.h"
88 #include "WebFormSubmissionListenerProxy.h"
89 #include "WebFramePolicyListenerProxy.h"
90 #include "WebFullScreenManagerProxy.h"
91 #include "WebFullScreenManagerProxyMessages.h"
92 #include "WebImage.h"
93 #include "WebInspectorProxy.h"
94 #include "WebInspectorUtilities.h"
95 #include "WebNavigationState.h"
96 #include "WebNotificationManagerProxy.h"
97 #include "WebOpenPanelResultListenerProxy.h"
98 #include "WebPageCreationParameters.h"
99 #include "WebPageGroup.h"
100 #include "WebPageGroupData.h"
101 #include "WebPageMessages.h"
102 #include "WebPageProxyMessages.h"
103 #include "WebPaymentCoordinatorProxy.h"
104 #include "WebPopupItem.h"
105 #include "WebPopupMenuProxy.h"
106 #include "WebPreferences.h"
107 #include "WebProcessMessages.h"
108 #include "WebProcessPool.h"
109 #include "WebProcessProxy.h"
110 #include "WebProtectionSpace.h"
111 #include "WebUserContentControllerProxy.h"
112 #include "WebsiteDataStore.h"
113 #include <WebCore/BitmapImage.h>
114 #include <WebCore/DiagnosticLoggingClient.h>
115 #include <WebCore/DragController.h>
116 #include <WebCore/DragData.h>
117 #include <WebCore/EventNames.h>
118 #include <WebCore/FloatRect.h>
119 #include <WebCore/FocusDirection.h>
120 #include <WebCore/JSDOMBinding.h>
121 #include <WebCore/MIMETypeRegistry.h>
122 #include <WebCore/RenderEmbeddedObject.h>
123 #include <WebCore/SerializedCryptoKeyWrap.h>
124 #include <WebCore/TextCheckerClient.h>
125 #include <WebCore/TextIndicator.h>
126 #include <WebCore/URL.h>
127 #include <WebCore/ValidationBubble.h>
128 #include <WebCore/WindowFeatures.h>
129 #include <stdio.h>
130 #include <wtf/NeverDestroyed.h>
131 #include <wtf/text/StringBuilder.h>
132 #include <wtf/text/StringView.h>
133
134 #if ENABLE(ASYNC_SCROLLING)
135 #include "RemoteScrollingCoordinatorProxy.h"
136 #endif
137
138 #if USE(COORDINATED_GRAPHICS_MULTIPROCESS)
139 #include "CoordinatedLayerTreeHostProxyMessages.h"
140 #endif
141
142 #if ENABLE(VIBRATION)
143 #include "WebVibrationProxy.h"
144 #endif
145
146 #ifndef NDEBUG
147 #include <wtf/RefCountedLeakCounter.h>
148 #endif
149
150 #if PLATFORM(COCOA)
151 #include "RemoteLayerTreeDrawingAreaProxy.h"
152 #include "RemoteLayerTreeScrollingPerformanceData.h"
153 #include "ViewSnapshotStore.h"
154 #include "WebVideoFullscreenManagerProxy.h"
155 #include "WebVideoFullscreenManagerProxyMessages.h"
156 #include <WebCore/MachSendRight.h>
157 #include <WebCore/RunLoopObserver.h>
158 #include <WebCore/TextIndicatorWindow.h>
159 #endif
160
161 #if PLATFORM(GTK)
162 #include "WebSelectionData.h"
163 #endif
164
165 #if USE(CAIRO)
166 #include <WebCore/CairoUtilities.h>
167 #endif
168
169 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
170 #include <WebCore/MediaPlaybackTarget.h>
171 #include <WebCore/WebMediaSessionManager.h>
172 #endif
173
174 #if ENABLE(MEDIA_SESSION)
175 #include "WebMediaSessionFocusManager.h"
176 #include "WebMediaSessionMetadata.h"
177 #include <WebCore/MediaSessionMetadata.h>
178 #endif
179
180 #if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
181 #include "WebPlaybackSessionManagerProxy.h"
182 #endif
183
184 #if ENABLE(MEDIA_STREAM)
185 #include <WebCore/MediaConstraintsImpl.h>
186 #endif
187
188 // This controls what strategy we use for mouse wheel coalescing.
189 #define MERGE_WHEEL_EVENTS 1
190
191 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, m_process->connection())
192 #define MESSAGE_CHECK_URL(url) MESSAGE_CHECK_BASE(m_process->checkURLReceivedFromWebProcess(url), m_process->connection())
193
194 #define RELEASE_LOG_IF_ALLOWED(...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), ProcessSuspension, __VA_ARGS__)
195
196 using namespace WebCore;
197
198 // Represents the number of wheel events we can hold in the queue before we start pushing them preemptively.
199 static const unsigned wheelEventQueueSizeThreshold = 10;
200
201 namespace WebKit {
202
203 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageProxyCounter, ("WebPageProxy"));
204
205 class ExceededDatabaseQuotaRecords {
206     WTF_MAKE_NONCOPYABLE(ExceededDatabaseQuotaRecords); WTF_MAKE_FAST_ALLOCATED;
207     friend class NeverDestroyed<ExceededDatabaseQuotaRecords>;
208 public:
209     struct Record {
210         uint64_t frameID;
211         String originIdentifier;
212         String databaseName;
213         String displayName;
214         uint64_t currentQuota;
215         uint64_t currentOriginUsage;
216         uint64_t currentDatabaseUsage;
217         uint64_t expectedUsage;
218         RefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply;
219     };
220
221     static ExceededDatabaseQuotaRecords& singleton();
222
223     std::unique_ptr<Record> createRecord(uint64_t frameID, String originIdentifier,
224         String databaseName, String displayName, uint64_t currentQuota,
225         uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, 
226         PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply>);
227
228     void add(std::unique_ptr<Record>);
229     bool areBeingProcessed() const { return !!m_currentRecord; }
230     Record* next();
231
232 private:
233     ExceededDatabaseQuotaRecords() { }
234     ~ExceededDatabaseQuotaRecords() { }
235
236     Deque<std::unique_ptr<Record>> m_records;
237     std::unique_ptr<Record> m_currentRecord;
238 };
239
240 ExceededDatabaseQuotaRecords& ExceededDatabaseQuotaRecords::singleton()
241 {
242     static NeverDestroyed<ExceededDatabaseQuotaRecords> records;
243     return records;
244 }
245
246 std::unique_ptr<ExceededDatabaseQuotaRecords::Record> ExceededDatabaseQuotaRecords::createRecord(
247     uint64_t frameID, String originIdentifier, String databaseName, String displayName,
248     uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage,
249     uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply)
250 {
251     auto record = std::make_unique<Record>();
252     record->frameID = frameID;
253     record->originIdentifier = originIdentifier;
254     record->databaseName = databaseName;
255     record->displayName = displayName;
256     record->currentQuota = currentQuota;
257     record->currentOriginUsage = currentOriginUsage;
258     record->currentDatabaseUsage = currentDatabaseUsage;
259     record->expectedUsage = expectedUsage;
260     record->reply = reply;
261     return record;
262 }
263
264 void ExceededDatabaseQuotaRecords::add(std::unique_ptr<ExceededDatabaseQuotaRecords::Record> record)
265 {
266     m_records.append(WTFMove(record));
267 }
268
269 ExceededDatabaseQuotaRecords::Record* ExceededDatabaseQuotaRecords::next()
270 {
271     m_currentRecord = nullptr;
272     if (!m_records.isEmpty())
273         m_currentRecord = m_records.takeFirst();
274     return m_currentRecord.get();
275 }
276
277 #if !LOG_DISABLED
278 static const char* webKeyboardEventTypeString(WebEvent::Type type)
279 {
280     switch (type) {
281     case WebEvent::KeyDown:
282         return "KeyDown";
283     
284     case WebEvent::KeyUp:
285         return "KeyUp";
286     
287     case WebEvent::RawKeyDown:
288         return "RawKeyDown";
289     
290     case WebEvent::Char:
291         return "Char";
292     
293     default:
294         ASSERT_NOT_REACHED();
295         return "<unknown>";
296     }
297 }
298 #endif // !LOG_DISABLED
299
300 class PageClientProtector {
301     WTF_MAKE_NONCOPYABLE(PageClientProtector);
302 public:
303     PageClientProtector(PageClient& pageClient)
304         : m_pageClient(pageClient)
305     {
306         m_pageClient.refView();
307     }
308
309     ~PageClientProtector()
310     {
311         m_pageClient.derefView();
312     }
313
314 private:
315     PageClient& m_pageClient;
316 };
317
318 Ref<WebPageProxy> WebPageProxy::create(PageClient& pageClient, WebProcessProxy& process, uint64_t pageID, Ref<API::PageConfiguration>&& configuration)
319 {
320     return adoptRef(*new WebPageProxy(pageClient, process, pageID, WTFMove(configuration)));
321 }
322
323 WebPageProxy::WebPageProxy(PageClient& pageClient, WebProcessProxy& process, uint64_t pageID, Ref<API::PageConfiguration>&& configuration)
324     : m_pageClient(pageClient)
325     , m_configuration(WTFMove(configuration))
326     , m_loaderClient(std::make_unique<API::LoaderClient>())
327     , m_policyClient(std::make_unique<API::PolicyClient>())
328     , m_formClient(std::make_unique<API::FormClient>())
329     , m_uiClient(std::make_unique<API::UIClient>())
330     , m_findClient(std::make_unique<API::FindClient>())
331     , m_findMatchesClient(std::make_unique<API::FindMatchesClient>())
332     , m_diagnosticLoggingClient(std::make_unique<API::DiagnosticLoggingClient>())
333 #if ENABLE(CONTEXT_MENUS)
334     , m_contextMenuClient(std::make_unique<API::ContextMenuClient>())
335 #endif
336     , m_navigationState(std::make_unique<WebNavigationState>())
337     , m_process(process)
338     , m_pageGroup(*m_configuration->pageGroup())
339     , m_preferences(*m_configuration->preferences())
340     , m_userContentController(*m_configuration->userContentController())
341     , m_visitedLinkStore(*m_configuration->visitedLinkStore())
342     , m_websiteDataStore(m_configuration->websiteDataStore()->websiteDataStore())
343     , m_mainFrame(nullptr)
344     , m_userAgent(standardUserAgent())
345     , m_treatsSHA1CertificatesAsInsecure(m_configuration->treatsSHA1SignedCertificatesAsInsecure())
346 #if ENABLE(FULLSCREEN_API)
347     , m_fullscreenClient(std::make_unique<API::FullscreenClient>())
348 #endif
349 #if PLATFORM(IOS)
350     , m_hasReceivedLayerTreeTransactionAfterDidCommitLoad(true)
351     , m_firstLayerTreeTransactionIdAfterDidCommitLoad(0)
352     , m_deviceOrientation(0)
353     , m_dynamicViewportSizeUpdateWaitingForTarget(false)
354     , m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit(false)
355     , m_dynamicViewportSizeUpdateLayerTreeTransactionID(0)
356     , m_layerTreeTransactionIdAtLastTouchStart(0)
357     , m_hasNetworkRequestsOnSuspended(false)
358 #endif
359     , m_geolocationPermissionRequestManager(*this)
360     , m_notificationPermissionRequestManager(*this)
361     , m_activityState(ActivityState::NoFlags)
362     , m_viewWasEverInWindow(false)
363 #if PLATFORM(IOS)
364     , m_alwaysRunsAtForegroundPriority(m_configuration->alwaysRunsAtForegroundPriority())
365 #endif
366     , m_initialCapitalizationEnabled(m_configuration->initialCapitalizationEnabled())
367     , m_backForwardList(WebBackForwardList::create(*this))
368     , m_maintainsInactiveSelection(false)
369     , m_waitsForPaintAfterViewDidMoveToWindow(m_configuration->waitsForPaintAfterViewDidMoveToWindow())
370     , m_isEditable(false)
371     , m_textZoomFactor(1)
372     , m_pageZoomFactor(1)
373     , m_pageScaleFactor(1)
374     , m_pluginZoomFactor(1)
375     , m_pluginScaleFactor(1)
376     , m_intrinsicDeviceScaleFactor(1)
377     , m_customDeviceScaleFactor(0)
378     , m_topContentInset(0)
379     , m_layerHostingMode(LayerHostingMode::InProcess)
380     , m_drawsBackground(true)
381     , m_useFixedLayout(false)
382     , m_suppressScrollbarAnimations(false)
383     , m_paginationMode(Pagination::Unpaginated)
384     , m_paginationBehavesLikeColumns(false)
385     , m_pageLength(0)
386     , m_gapBetweenPages(0)
387     , m_paginationLineGridEnabled(false)
388     , m_isValid(true)
389     , m_isClosed(false)
390     , m_canRunModal(false)
391     , m_isInPrintingMode(false)
392     , m_isPerformingDOMPrintOperation(false)
393     , m_inDecidePolicyForResponseSync(false)
394     , m_decidePolicyForResponseRequest(0)
395     , m_syncMimeTypePolicyActionIsValid(false)
396     , m_syncMimeTypePolicyAction(PolicyUse)
397     , m_syncMimeTypePolicyDownloadID(0)
398     , m_inDecidePolicyForNavigationAction(false)
399     , m_syncNavigationActionPolicyActionIsValid(false)
400     , m_syncNavigationActionPolicyAction(PolicyUse)
401     , m_syncNavigationActionPolicyDownloadID(0)
402     , m_processingMouseMoveEvent(false)
403     , m_pageID(pageID)
404     , m_sessionID(m_configuration->sessionID())
405     , m_isPageSuspended(false)
406     , m_addsVisitedLinks(true)
407     , m_controlledByAutomation(m_configuration->isControlledByAutomation())
408 #if ENABLE(REMOTE_INSPECTOR)
409     , m_allowsRemoteInspection(true)
410 #endif
411 #if PLATFORM(COCOA)
412     , m_isSmartInsertDeleteEnabled(TextChecker::isSmartInsertDeleteEnabled())
413 #endif
414 #if PLATFORM(GTK)
415     , m_backgroundColor(Color::white)
416 #endif
417     , m_spellDocumentTag(0)
418     , m_hasSpellDocumentTag(false)
419     , m_pendingLearnOrIgnoreWordMessageCount(0)
420     , m_mainFrameHasCustomContentProvider(false)
421 #if ENABLE(DRAG_SUPPORT)
422     , m_currentDragOperation(DragOperationNone)
423     , m_currentDragIsOverFileInput(false)
424     , m_currentDragNumberOfFilesToBeAccepted(0)
425 #endif
426     , m_pageLoadState(*this)
427     , m_delegatesScrolling(false)
428     , m_mainFrameHasHorizontalScrollbar(false)
429     , m_mainFrameHasVerticalScrollbar(false)
430     , m_canShortCircuitHorizontalWheelEvents(true)
431     , m_mainFrameIsPinnedToLeftSide(true)
432     , m_mainFrameIsPinnedToRightSide(true)
433     , m_mainFrameIsPinnedToTopSide(true)
434     , m_mainFrameIsPinnedToBottomSide(true)
435     , m_shouldUseImplicitRubberBandControl(false)
436     , m_rubberBandsAtLeft(true)
437     , m_rubberBandsAtRight(true)
438     , m_rubberBandsAtTop(true)
439     , m_rubberBandsAtBottom(true)
440     , m_enableVerticalRubberBanding(true)
441     , m_enableHorizontalRubberBanding(true)
442     , m_backgroundExtendsBeyondPage(false)
443     , m_shouldRecordNavigationSnapshots(false)
444     , m_isShowingNavigationGestureSnapshot(false)
445     , m_pageCount(0)
446     , m_renderTreeSize(0)
447     , m_sessionRestorationRenderTreeSize(0)
448     , m_hitRenderTreeSizeThreshold(false)
449     , m_suppressVisibilityUpdates(false)
450     , m_autoSizingShouldExpandToViewHeight(false)
451     , m_mediaVolume(1)
452     , m_mayStartMediaWhenInWindow(true)
453     , m_waitingForDidUpdateActivityState(false)
454 #if PLATFORM(COCOA)
455     , m_scrollPerformanceDataCollectionEnabled(false)
456 #endif
457     , m_scrollPinningBehavior(DoNotPin)
458     , m_navigationID(0)
459     , m_configurationPreferenceValues(m_configuration->preferenceValues())
460     , m_potentiallyChangedActivityStateFlags(ActivityState::NoFlags)
461     , m_activityStateChangeWantsSynchronousReply(false)
462     , m_weakPtrFactory(this)
463 {
464     m_webProcessLifetimeTracker.addObserver(m_visitedLinkStore);
465     m_webProcessLifetimeTracker.addObserver(m_websiteDataStore);
466
467     updateActivityState();
468     updateThrottleState();
469     updateHiddenPageThrottlingAutoIncreases();
470     
471 #if HAVE(OUT_OF_PROCESS_LAYER_HOSTING)
472     m_layerHostingMode = m_activityState & ActivityState::IsInWindow ? m_pageClient.viewLayerHostingMode() : LayerHostingMode::OutOfProcess;
473 #endif
474
475     platformInitialize();
476
477 #ifndef NDEBUG
478     webPageProxyCounter.increment();
479 #endif
480
481     WebProcessPool::statistics().wkPageCount++;
482
483     m_preferences->addPage(*this);
484     m_pageGroup->addPage(this);
485
486     m_inspector = WebInspectorProxy::create(this);
487 #if ENABLE(FULLSCREEN_API)
488     m_fullScreenManager = WebFullScreenManagerProxy::create(*this, m_pageClient.fullScreenManagerProxyClient());
489 #endif
490 #if PLATFORM(IOS) && HAVE(AVKIT) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
491     m_playbackSessionManager = WebPlaybackSessionManagerProxy::create(*this);
492     m_videoFullscreenManager = WebVideoFullscreenManagerProxy::create(*this, *m_playbackSessionManager);
493 #endif
494 #if ENABLE(VIBRATION)
495     m_vibration = WebVibrationProxy::create(this);
496 #endif
497
498 #if ENABLE(APPLE_PAY)
499     m_paymentCoordinator = std::make_unique<WebPaymentCoordinatorProxy>(*this);
500 #endif
501
502     m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, *this);
503
504     if (m_sessionID.isEphemeral()) {
505         m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::EnsurePrivateBrowsingSession(m_sessionID));
506         m_process->processPool().sendToAllProcesses(Messages::WebProcess::EnsurePrivateBrowsingSession(m_sessionID));
507     }
508
509 #if PLATFORM(COCOA)
510     const CFIndex activityStateChangeRunLoopOrder = (CFIndex)RunLoopObserver::WellKnownRunLoopOrders::CoreAnimationCommit - 1;
511     m_activityStateChangeDispatcher = std::make_unique<RunLoopObserver>(activityStateChangeRunLoopOrder, [this] {
512         this->dispatchActivityStateChange();
513     });
514 #endif
515 }
516
517 WebPageProxy::~WebPageProxy()
518 {
519     ASSERT(m_process->webPage(m_pageID) != this);
520 #if !ASSERT_DISABLED
521     for (WebPageProxy* page : m_process->pages())
522         ASSERT(page != this);
523 #endif
524
525     if (!m_isClosed)
526         close();
527
528     WebProcessPool::statistics().wkPageCount--;
529
530     if (m_hasSpellDocumentTag)
531         TextChecker::closeSpellDocumentWithTag(m_spellDocumentTag);
532
533     m_preferences->removePage(*this);
534     m_pageGroup->removePage(this);
535
536 #ifndef NDEBUG
537     webPageProxyCounter.decrement();
538 #endif
539 }
540
541 const API::PageConfiguration& WebPageProxy::configuration() const
542 {
543     return m_configuration.get();
544 }
545
546 pid_t WebPageProxy::processIdentifier() const
547 {
548     if (m_isClosed)
549         return 0;
550
551     return m_process->processIdentifier();
552 }
553
554 bool WebPageProxy::isValid() const
555 {
556     // A page that has been explicitly closed is never valid.
557     if (m_isClosed)
558         return false;
559
560     return m_isValid;
561 }
562
563 void WebPageProxy::setPreferences(WebPreferences& preferences)
564 {
565     if (&preferences == m_preferences.ptr())
566         return;
567
568     m_preferences->removePage(*this);
569     m_preferences = preferences;
570     m_preferences->addPage(*this);
571
572     preferencesDidChange();
573 }
574     
575 void WebPageProxy::setHistoryClient(std::unique_ptr<API::HistoryClient> historyClient)
576 {
577     m_historyClient = WTFMove(historyClient);
578 }
579
580 void WebPageProxy::setNavigationClient(std::unique_ptr<API::NavigationClient> navigationClient)
581 {
582     m_navigationClient = WTFMove(navigationClient);
583 }
584
585 void WebPageProxy::setLoaderClient(std::unique_ptr<API::LoaderClient> loaderClient)
586 {
587     if (!loaderClient) {
588         m_loaderClient = std::make_unique<API::LoaderClient>();
589         return;
590     }
591
592     m_loaderClient = WTFMove(loaderClient);
593 }
594
595 void WebPageProxy::setPolicyClient(std::unique_ptr<API::PolicyClient> policyClient)
596 {
597     if (!policyClient) {
598         m_policyClient = std::make_unique<API::PolicyClient>();
599         return;
600     }
601
602     m_policyClient = WTFMove(policyClient);
603 }
604
605 void WebPageProxy::setFormClient(std::unique_ptr<API::FormClient> formClient)
606 {
607     if (!formClient) {
608         m_formClient = std::make_unique<API::FormClient>();
609         return;
610     }
611
612     m_formClient = WTFMove(formClient);
613 }
614
615 void WebPageProxy::setUIClient(std::unique_ptr<API::UIClient> uiClient)
616 {
617     if (!uiClient) {
618         m_uiClient = std::make_unique<API::UIClient>();
619         return;
620     }
621
622     m_uiClient = WTFMove(uiClient);
623
624     if (!isValid())
625         return;
626
627     m_process->send(Messages::WebPage::SetCanRunBeforeUnloadConfirmPanel(m_uiClient->canRunBeforeUnloadConfirmPanel()), m_pageID);
628     setCanRunModal(m_uiClient->canRunModal());
629 }
630
631 void WebPageProxy::setIconLoadingClient(std::unique_ptr<API::IconLoadingClient> iconLoadingClient)
632 {
633     bool hasClient = iconLoadingClient.get();
634     if (!iconLoadingClient)
635         m_iconLoadingClient = std::make_unique<API::IconLoadingClient>();
636     else
637         m_iconLoadingClient = WTFMove(iconLoadingClient);
638
639     if (!isValid())
640         return;
641
642     m_process->send(Messages::WebPage::SetUseIconLoadingClient(hasClient), m_pageID);
643 }
644
645 void WebPageProxy::setFindClient(std::unique_ptr<API::FindClient> findClient)
646 {
647     if (!findClient) {
648         m_findClient = std::make_unique<API::FindClient>();
649         return;
650     }
651     
652     m_findClient = WTFMove(findClient);
653 }
654
655 void WebPageProxy::setFindMatchesClient(std::unique_ptr<API::FindMatchesClient> findMatchesClient)
656 {
657     if (!findMatchesClient) {
658         m_findMatchesClient = std::make_unique<API::FindMatchesClient>();
659         return;
660     }
661
662     m_findMatchesClient = WTFMove(findMatchesClient);
663 }
664
665 void WebPageProxy::setDiagnosticLoggingClient(std::unique_ptr<API::DiagnosticLoggingClient> diagnosticLoggingClient)
666 {
667     if (!diagnosticLoggingClient) {
668         m_diagnosticLoggingClient = std::make_unique<API::DiagnosticLoggingClient>();
669         return;
670     }
671
672     m_diagnosticLoggingClient = WTFMove(diagnosticLoggingClient);
673 }
674
675 #if ENABLE(CONTEXT_MENUS)
676 void WebPageProxy::setContextMenuClient(std::unique_ptr<API::ContextMenuClient> contextMenuClient)
677 {
678     if (!contextMenuClient) {
679         m_contextMenuClient = std::make_unique<API::ContextMenuClient>();
680         return;
681     }
682
683     m_contextMenuClient = WTFMove(contextMenuClient);
684 }
685 #endif
686
687 void WebPageProxy::setInjectedBundleClient(const WKPageInjectedBundleClientBase* client)
688 {
689     if (!client) {
690         m_injectedBundleClient = nullptr;
691         return;
692     }
693
694     m_injectedBundleClient = std::make_unique<WebPageInjectedBundleClient>();
695     m_injectedBundleClient->initialize(client);
696 }
697
698 void WebPageProxy::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
699 {
700     ASSERT(m_process->connection() == &connection);
701
702     if (!m_injectedBundleClient)
703         return;
704
705     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(this, messageName, m_process->transformHandlesToObjects(messageBody.object()).get());
706 }
707
708 void WebPageProxy::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, UserData& returnUserData)
709 {
710     ASSERT(m_process->connection() == &connection);
711
712     if (!m_injectedBundleClient)
713         return;
714
715     RefPtr<API::Object> returnData;
716     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(this, messageName, m_process->transformHandlesToObjects(messageBody.object()).get(), returnData);
717     returnUserData = UserData(m_process->transformObjectsToHandles(returnData.get()));
718 }
719
720 void WebPageProxy::reattachToWebProcess()
721 {
722     ASSERT(!m_isClosed);
723     ASSERT(!isValid());
724     ASSERT(m_process->state() == WebProcessProxy::State::Terminated);
725
726     m_isValid = true;
727     m_process->removeWebPage(m_pageID);
728     m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID);
729
730     m_process = m_process->processPool().createNewWebProcessRespectingProcessCountLimit();
731
732     ASSERT(m_process->state() != ChildProcessProxy::State::Terminated);
733     if (m_process->state() == ChildProcessProxy::State::Running)
734         processDidFinishLaunching();
735     m_process->addExistingWebPage(this, m_pageID);
736     m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, *this);
737
738     updateActivityState();
739     updateThrottleState();
740
741     m_inspector = WebInspectorProxy::create(this);
742 #if ENABLE(FULLSCREEN_API)
743     m_fullScreenManager = WebFullScreenManagerProxy::create(*this, m_pageClient.fullScreenManagerProxyClient());
744 #endif
745 #if PLATFORM(IOS) && HAVE(AVKIT) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
746     m_playbackSessionManager = WebPlaybackSessionManagerProxy::create(*this);
747     m_videoFullscreenManager = WebVideoFullscreenManagerProxy::create(*this, *m_playbackSessionManager);
748 #endif
749
750 #if ENABLE(APPLE_PAY)
751     m_paymentCoordinator = std::make_unique<WebPaymentCoordinatorProxy>(*this);
752 #endif
753
754     initializeWebPage();
755
756     m_pageClient.didRelaunchProcess();
757     m_drawingArea->waitForBackingStoreUpdateOnNextPaint();
758 }
759
760 RefPtr<API::Navigation> WebPageProxy::reattachToWebProcessForReload()
761 {
762     if (m_isClosed)
763         return nullptr;
764     
765     ASSERT(!isValid());
766     reattachToWebProcess();
767
768     if (!m_backForwardList->currentItem())
769         return nullptr;
770
771     auto navigation = m_navigationState->createReloadNavigation();
772
773     // We allow stale content when reloading a WebProcess that's been killed or crashed.
774     m_process->send(Messages::WebPage::GoToBackForwardItem(navigation->navigationID(), m_backForwardList->currentItem()->itemID()), m_pageID);
775     m_process->responsivenessTimer().start();
776
777     return WTFMove(navigation);
778 }
779
780 RefPtr<API::Navigation> WebPageProxy::reattachToWebProcessWithItem(WebBackForwardListItem* item)
781 {
782     if (m_isClosed)
783         return nullptr;
784
785     ASSERT(!isValid());
786     reattachToWebProcess();
787
788     if (!item)
789         return nullptr;
790
791     if (item != m_backForwardList->currentItem())
792         m_backForwardList->goToItem(item);
793
794     auto navigation = m_navigationState->createBackForwardNavigation();
795
796     m_process->send(Messages::WebPage::GoToBackForwardItem(navigation->navigationID(), item->itemID()), m_pageID);
797     m_process->responsivenessTimer().start();
798
799     return WTFMove(navigation);
800 }
801
802 void WebPageProxy::initializeWebPage()
803 {
804     ASSERT(isValid());
805
806     BackForwardListItemVector items = m_backForwardList->entries();
807     for (size_t i = 0; i < items.size(); ++i)
808         m_process->registerNewWebBackForwardListItem(items[i].get());
809
810     m_drawingArea = m_pageClient.createDrawingAreaProxy();
811     ASSERT(m_drawingArea);
812
813 #if ENABLE(ASYNC_SCROLLING)
814     if (m_drawingArea->type() == DrawingAreaTypeRemoteLayerTree) {
815         m_scrollingCoordinatorProxy = std::make_unique<RemoteScrollingCoordinatorProxy>(*this);
816 #if PLATFORM(IOS)
817         // On iOS, main frame scrolls are sent in terms of visible rect updates.
818         m_scrollingCoordinatorProxy->setPropagatesMainFrameScrolls(false);
819 #endif
820     }
821 #endif
822
823 #if ENABLE(INSPECTOR_SERVER)
824     if (m_preferences->developerExtrasEnabled())
825         inspector()->enableRemoteInspection();
826 #endif
827
828     process().send(Messages::WebProcess::CreateWebPage(m_pageID, creationParameters()), 0);
829
830 #if PLATFORM(COCOA)
831     send(Messages::WebPage::SetSmartInsertDeleteEnabled(m_isSmartInsertDeleteEnabled));
832 #endif
833
834     m_needsToFinishInitializingWebPageAfterProcessLaunch = true;
835     finishInitializingWebPageAfterProcessLaunch();
836 }
837
838 void WebPageProxy::finishInitializingWebPageAfterProcessLaunch()
839 {
840     if (!m_needsToFinishInitializingWebPageAfterProcessLaunch)
841         return;
842     if (m_process->state() != WebProcessProxy::State::Running)
843         return;
844
845     m_needsToFinishInitializingWebPageAfterProcessLaunch = false;
846
847     m_process->addWebUserContentControllerProxy(m_userContentController);
848     m_process->addVisitedLinkStore(m_visitedLinkStore);
849 }
850
851 void WebPageProxy::close()
852 {
853     if (m_isClosed)
854         return;
855
856     m_isClosed = true;
857
858     if (m_activePopupMenu)
859         m_activePopupMenu->cancelTracking();
860
861 #if ENABLE(CONTEXT_MENUS)
862     m_activeContextMenu = nullptr;
863 #endif
864
865     m_backForwardList->pageClosed();
866     m_pageClient.pageClosed();
867
868     m_process->disconnectFramesFromPage(this);
869
870     resetState(ResetStateReason::PageInvalidated);
871
872     m_loaderClient = std::make_unique<API::LoaderClient>();
873     m_navigationClient = nullptr;
874     m_policyClient = std::make_unique<API::PolicyClient>();
875     m_formClient = std::make_unique<API::FormClient>();
876     m_uiClient = std::make_unique<API::UIClient>();
877     m_findClient = std::make_unique<API::FindClient>();
878     m_findMatchesClient = std::make_unique<API::FindMatchesClient>();
879     m_diagnosticLoggingClient = std::make_unique<API::DiagnosticLoggingClient>();
880 #if ENABLE(CONTEXT_MENUS)
881     m_contextMenuClient = std::make_unique<API::ContextMenuClient>();
882 #endif
883
884     m_webProcessLifetimeTracker.pageWasInvalidated();
885
886     m_process->send(Messages::WebPage::Close(), m_pageID);
887     m_process->removeWebPage(m_pageID);
888     m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID);
889     m_process->processPool().supplement<WebNotificationManagerProxy>()->clearNotifications(this);
890
891     // Null out related WebPageProxy to avoid leaks.
892     m_configuration->setRelatedPage(nullptr);
893
894 #if PLATFORM(IOS)
895     // Make sure we don't hold a process assertion after getting closed.
896     m_activityToken = nullptr;
897 #endif
898 }
899
900 bool WebPageProxy::tryClose()
901 {
902     if (!isValid())
903         return true;
904
905     // Close without delay if the process allows it. Our goal is to terminate
906     // the process, so we check a per-process status bit.
907     if (m_process->isSuddenTerminationEnabled())
908         return true;
909
910     m_process->send(Messages::WebPage::TryClose(), m_pageID);
911     m_process->responsivenessTimer().start();
912     return false;
913 }
914
915 bool WebPageProxy::maybeInitializeSandboxExtensionHandle(const URL& url, SandboxExtension::Handle& sandboxExtensionHandle)
916 {
917     if (!url.isLocalFile())
918         return false;
919
920     if (m_process->hasAssumedReadAccessToURL(url))
921         return false;
922
923     // Inspector resources are in a directory with assumed access.
924     ASSERT_WITH_SECURITY_IMPLICATION(!WebKit::isInspectorPage(*this));
925
926     SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
927     return true;
928 }
929
930 #if !PLATFORM(COCOA)
931 void WebPageProxy::addPlatformLoadParameters(LoadParameters&)
932 {
933 }
934 #endif
935
936 RefPtr<API::Navigation> WebPageProxy::loadRequest(const ResourceRequest& request, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy, API::Object* userData)
937 {
938     if (m_isClosed)
939         return nullptr;
940
941     auto navigation = m_navigationState->createLoadRequestNavigation(request);
942
943     auto transaction = m_pageLoadState.transaction();
944
945     m_pageLoadState.setPendingAPIRequestURL(transaction, request.url());
946
947     if (!isValid())
948         reattachToWebProcess();
949
950     LoadParameters loadParameters;
951     loadParameters.navigationID = navigation->navigationID();
952     loadParameters.request = request;
953     loadParameters.shouldOpenExternalURLsPolicy = (uint64_t)shouldOpenExternalURLsPolicy;
954     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
955     bool createdExtension = maybeInitializeSandboxExtensionHandle(request.url(), loadParameters.sandboxExtensionHandle);
956     if (createdExtension)
957         m_process->willAcquireUniversalFileReadSandboxExtension();
958     addPlatformLoadParameters(loadParameters);
959
960     m_process->send(Messages::WebPage::LoadRequest(loadParameters), m_pageID);
961     m_process->responsivenessTimer().start();
962
963     return WTFMove(navigation);
964 }
965
966 RefPtr<API::Navigation> WebPageProxy::loadFile(const String& fileURLString, const String& resourceDirectoryURLString, API::Object* userData)
967 {
968     if (m_isClosed)
969         return nullptr;
970
971     if (!isValid())
972         reattachToWebProcess();
973
974     URL fileURL = URL(URL(), fileURLString);
975     if (!fileURL.isLocalFile())
976         return nullptr;
977
978     URL resourceDirectoryURL;
979     if (resourceDirectoryURLString.isNull())
980         resourceDirectoryURL = URL(ParsedURLString, ASCIILiteral("file:///"));
981     else {
982         resourceDirectoryURL = URL(URL(), resourceDirectoryURLString);
983         if (!resourceDirectoryURL.isLocalFile())
984             return nullptr;
985     }
986
987     auto navigation = m_navigationState->createLoadRequestNavigation(ResourceRequest(fileURL));
988
989     auto transaction = m_pageLoadState.transaction();
990
991     m_pageLoadState.setPendingAPIRequestURL(transaction, fileURLString);
992
993     String resourceDirectoryPath = resourceDirectoryURL.fileSystemPath();
994
995     LoadParameters loadParameters;
996     loadParameters.navigationID = navigation->navigationID();
997     loadParameters.request = fileURL;
998     loadParameters.shouldOpenExternalURLsPolicy = (uint64_t)ShouldOpenExternalURLsPolicy::ShouldNotAllow;
999     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
1000     SandboxExtension::createHandle(resourceDirectoryPath, SandboxExtension::ReadOnly, loadParameters.sandboxExtensionHandle);
1001     addPlatformLoadParameters(loadParameters);
1002
1003     m_process->assumeReadAccessToBaseURL(resourceDirectoryURL);
1004     m_process->send(Messages::WebPage::LoadRequest(loadParameters), m_pageID);
1005     m_process->responsivenessTimer().start();
1006
1007     return WTFMove(navigation);
1008 }
1009
1010 RefPtr<API::Navigation> WebPageProxy::loadData(API::Data* data, const String& MIMEType, const String& encoding, const String& baseURL, API::Object* userData)
1011 {
1012     if (m_isClosed)
1013         return nullptr;
1014
1015     auto navigation = m_navigationState->createLoadDataNavigation();
1016
1017     auto transaction = m_pageLoadState.transaction();
1018
1019     m_pageLoadState.setPendingAPIRequestURL(transaction, !baseURL.isEmpty() ? baseURL : blankURL().string());
1020
1021     if (!isValid())
1022         reattachToWebProcess();
1023
1024     LoadParameters loadParameters;
1025     loadParameters.navigationID = navigation->navigationID();
1026     loadParameters.data = data->dataReference();
1027     loadParameters.MIMEType = MIMEType;
1028     loadParameters.encodingName = encoding;
1029     loadParameters.baseURLString = baseURL;
1030     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
1031     addPlatformLoadParameters(loadParameters);
1032
1033     m_process->assumeReadAccessToBaseURL(baseURL);
1034     m_process->send(Messages::WebPage::LoadData(loadParameters), m_pageID);
1035     m_process->responsivenessTimer().start();
1036
1037     return WTFMove(navigation);
1038 }
1039
1040 // FIXME: Get rid of loadHTMLString and just use loadData instead.
1041 RefPtr<API::Navigation> WebPageProxy::loadHTMLString(const String& htmlString, const String& baseURL, API::Object* userData)
1042 {
1043     if (m_isClosed)
1044         return nullptr;
1045
1046     auto navigation = m_navigationState->createLoadDataNavigation();
1047
1048     auto transaction = m_pageLoadState.transaction();
1049
1050     m_pageLoadState.setPendingAPIRequestURL(transaction, !baseURL.isEmpty() ? baseURL : blankURL().string());
1051
1052     if (!isValid())
1053         reattachToWebProcess();
1054
1055     LoadParameters loadParameters;
1056     loadParameters.navigationID = navigation->navigationID();
1057     loadParameters.string = htmlString;
1058     loadParameters.MIMEType = ASCIILiteral("text/html");
1059     loadParameters.baseURLString = baseURL;
1060     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
1061     addPlatformLoadParameters(loadParameters);
1062
1063     m_process->assumeReadAccessToBaseURL(baseURL);
1064     m_process->send(Messages::WebPage::LoadString(loadParameters), m_pageID);
1065     m_process->responsivenessTimer().start();
1066
1067     return WTFMove(navigation);
1068 }
1069
1070 void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, API::Object* userData)
1071 {
1072     // When the UIProcess is in the process of handling a failing provisional load, do not attempt to
1073     // start a second alternative HTML load as this will prevent the page load state from being
1074     // handled properly.
1075     if (m_isClosed || m_isLoadingAlternateHTMLStringForFailingProvisionalLoad)
1076         return;
1077
1078     if (!m_failingProvisionalLoadURL.isEmpty())
1079         m_isLoadingAlternateHTMLStringForFailingProvisionalLoad = true;
1080
1081     if (!isValid())
1082         reattachToWebProcess();
1083
1084     auto transaction = m_pageLoadState.transaction();
1085
1086     m_pageLoadState.setPendingAPIRequestURL(transaction, unreachableURL);
1087     m_pageLoadState.setUnreachableURL(transaction, unreachableURL);
1088
1089     if (m_mainFrame)
1090         m_mainFrame->setUnreachableURL(unreachableURL);
1091
1092     LoadParameters loadParameters;
1093     loadParameters.navigationID = 0;
1094     loadParameters.string = htmlString;
1095     loadParameters.baseURLString = baseURL;
1096     loadParameters.unreachableURLString = unreachableURL;
1097     loadParameters.provisionalLoadErrorURLString = m_failingProvisionalLoadURL;
1098     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
1099     addPlatformLoadParameters(loadParameters);
1100
1101     m_process->assumeReadAccessToBaseURL(baseURL);
1102     m_process->assumeReadAccessToBaseURL(unreachableURL);
1103     m_process->send(Messages::WebPage::LoadAlternateHTMLString(loadParameters), m_pageID);
1104     m_process->responsivenessTimer().start();
1105 }
1106
1107 void WebPageProxy::loadPlainTextString(const String& string, API::Object* userData)
1108 {
1109     if (m_isClosed)
1110         return;
1111
1112     if (!isValid())
1113         reattachToWebProcess();
1114
1115     auto transaction = m_pageLoadState.transaction();
1116     m_pageLoadState.setPendingAPIRequestURL(transaction, blankURL().string());
1117
1118     LoadParameters loadParameters;
1119     loadParameters.navigationID = 0;
1120     loadParameters.string = string;
1121     loadParameters.MIMEType = ASCIILiteral("text/plain");
1122     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
1123     addPlatformLoadParameters(loadParameters);
1124
1125     m_process->send(Messages::WebPage::LoadString(loadParameters), m_pageID);
1126     m_process->responsivenessTimer().start();
1127 }
1128
1129 void WebPageProxy::loadWebArchiveData(API::Data* webArchiveData, API::Object* userData)
1130 {
1131     if (m_isClosed)
1132         return;
1133
1134     if (!isValid())
1135         reattachToWebProcess();
1136
1137     auto transaction = m_pageLoadState.transaction();
1138     m_pageLoadState.setPendingAPIRequestURL(transaction, blankURL().string());
1139
1140     LoadParameters loadParameters;
1141     loadParameters.navigationID = 0;
1142     loadParameters.data = webArchiveData->dataReference();
1143     loadParameters.MIMEType = ASCIILiteral("application/x-webarchive");
1144     loadParameters.encodingName = ASCIILiteral("utf-16");
1145     loadParameters.userData = UserData(process().transformObjectsToHandles(userData).get());
1146     addPlatformLoadParameters(loadParameters);
1147
1148     m_process->send(Messages::WebPage::LoadData(loadParameters), m_pageID);
1149     m_process->responsivenessTimer().start();
1150 }
1151
1152 void WebPageProxy::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint)
1153 {
1154     if (m_isClosed)
1155         return;
1156
1157     if (WebCore::protocolIsJavaScript(url))
1158         return;
1159
1160     if (!isValid())
1161         reattachToWebProcess();
1162
1163     m_process->send(Messages::WebPage::NavigateToPDFLinkWithSimulatedClick(url, documentPoint, screenPoint), m_pageID);
1164     m_process->responsivenessTimer().start();
1165 }
1166
1167 void WebPageProxy::stopLoading()
1168 {
1169     if (!isValid())
1170         return;
1171
1172     m_process->send(Messages::WebPage::StopLoading(), m_pageID);
1173     m_process->responsivenessTimer().start();
1174 }
1175
1176 RefPtr<API::Navigation> WebPageProxy::reload(bool reloadFromOrigin, bool contentBlockersEnabled)
1177 {
1178     SandboxExtension::Handle sandboxExtensionHandle;
1179
1180     String url = m_pageLoadState.activeURL();
1181     if (url.isEmpty() && m_backForwardList->currentItem())
1182         url = m_backForwardList->currentItem()->url();
1183
1184     if (!url.isEmpty()) {
1185         auto transaction = m_pageLoadState.transaction();
1186         m_pageLoadState.setPendingAPIRequestURL(transaction, url);
1187
1188         // We may not have an extension yet if back/forward list was reinstated after a WebProcess crash or a browser relaunch
1189         bool createdExtension = maybeInitializeSandboxExtensionHandle(URL(URL(), url), sandboxExtensionHandle);
1190         if (createdExtension)
1191             m_process->willAcquireUniversalFileReadSandboxExtension();
1192     }
1193
1194     if (!isValid())
1195         return reattachToWebProcessForReload();
1196     
1197     auto navigation = m_navigationState->createReloadNavigation();
1198
1199     m_process->send(Messages::WebPage::Reload(navigation->navigationID(), reloadFromOrigin, contentBlockersEnabled, sandboxExtensionHandle), m_pageID);
1200     m_process->responsivenessTimer().start();
1201
1202     return WTFMove(navigation);
1203 }
1204
1205 void WebPageProxy::recordAutomaticNavigationSnapshot()
1206 {
1207     if (m_suppressAutomaticNavigationSnapshotting)
1208         return;
1209
1210     if (WebBackForwardListItem* item = m_backForwardList->currentItem())
1211         recordNavigationSnapshot(*item);
1212 }
1213
1214 void WebPageProxy::recordNavigationSnapshot(WebBackForwardListItem& item)
1215 {
1216     if (!m_shouldRecordNavigationSnapshots)
1217         return;
1218
1219 #if PLATFORM(COCOA)
1220     ViewSnapshotStore::singleton().recordSnapshot(*this, item);
1221 #else
1222     UNUSED_PARAM(item);
1223 #endif
1224 }
1225
1226 RefPtr<API::Navigation> WebPageProxy::goForward()
1227 {
1228     WebBackForwardListItem* forwardItem = m_backForwardList->forwardItem();
1229     if (!forwardItem)
1230         return nullptr;
1231
1232     auto transaction = m_pageLoadState.transaction();
1233
1234     m_pageLoadState.setPendingAPIRequestURL(transaction, forwardItem->url());
1235
1236     if (!isValid())
1237         return reattachToWebProcessWithItem(forwardItem);
1238
1239     RefPtr<API::Navigation> navigation;
1240     if (!m_backForwardList->currentItem()->itemIsInSameDocument(*forwardItem))
1241         navigation = m_navigationState->createBackForwardNavigation();
1242
1243     m_process->send(Messages::WebPage::GoForward(navigation ? navigation->navigationID() : 0, forwardItem->itemID()), m_pageID);
1244     m_process->responsivenessTimer().start();
1245
1246     return navigation;
1247 }
1248
1249 RefPtr<API::Navigation> WebPageProxy::goBack()
1250 {
1251     WebBackForwardListItem* backItem = m_backForwardList->backItem();
1252     if (!backItem)
1253         return nullptr;
1254
1255     auto transaction = m_pageLoadState.transaction();
1256
1257     m_pageLoadState.setPendingAPIRequestURL(transaction, backItem->url());
1258
1259     if (!isValid())
1260         return reattachToWebProcessWithItem(backItem);
1261
1262     RefPtr<API::Navigation> navigation;
1263     if (!m_backForwardList->currentItem()->itemIsInSameDocument(*backItem))
1264         navigation = m_navigationState->createBackForwardNavigation();
1265
1266     m_process->send(Messages::WebPage::GoBack(navigation ? navigation->navigationID() : 0, backItem->itemID()), m_pageID);
1267     m_process->responsivenessTimer().start();
1268
1269     return navigation;
1270 }
1271
1272 RefPtr<API::Navigation> WebPageProxy::goToBackForwardItem(WebBackForwardListItem* item)
1273 {
1274     if (!isValid())
1275         return reattachToWebProcessWithItem(item);
1276
1277     auto transaction = m_pageLoadState.transaction();
1278
1279     m_pageLoadState.setPendingAPIRequestURL(transaction, item->url());
1280
1281     RefPtr<API::Navigation> navigation;
1282     if (!m_backForwardList->currentItem()->itemIsInSameDocument(*item))
1283         navigation = m_navigationState->createBackForwardNavigation();
1284
1285     m_process->send(Messages::WebPage::GoToBackForwardItem(navigation ? navigation->navigationID() : 0, item->itemID()), m_pageID);
1286     m_process->responsivenessTimer().start();
1287
1288     return navigation;
1289 }
1290
1291 void WebPageProxy::tryRestoreScrollPosition()
1292 {
1293     if (!isValid())
1294         return;
1295
1296     m_process->send(Messages::WebPage::TryRestoreScrollPosition(), m_pageID);
1297 }
1298
1299 void WebPageProxy::didChangeBackForwardList(WebBackForwardListItem* added, Vector<RefPtr<WebBackForwardListItem>> removed)
1300 {
1301     PageClientProtector protector(m_pageClient);
1302
1303     m_loaderClient->didChangeBackForwardList(*this, added, WTFMove(removed));
1304
1305     auto transaction = m_pageLoadState.transaction();
1306
1307     m_pageLoadState.setCanGoBack(transaction, m_backForwardList->backItem());
1308     m_pageLoadState.setCanGoForward(transaction, m_backForwardList->forwardItem());
1309 }
1310
1311 void WebPageProxy::willGoToBackForwardListItem(uint64_t itemID, const UserData& userData)
1312 {
1313     PageClientProtector protector(m_pageClient);
1314
1315     if (WebBackForwardListItem* item = m_process->webBackForwardItem(itemID))
1316         m_loaderClient->willGoToBackForwardListItem(*this, item, m_process->transformHandlesToObjects(userData.object()).get());
1317 }
1318
1319 bool WebPageProxy::shouldKeepCurrentBackForwardListItemInList(WebBackForwardListItem* item)
1320 {
1321     PageClientProtector protector(m_pageClient);
1322
1323     return m_loaderClient->shouldKeepCurrentBackForwardListItemInList(*this, item);
1324 }
1325
1326 bool WebPageProxy::canShowMIMEType(const String& mimeType)
1327 {
1328     if (MIMETypeRegistry::canShowMIMEType(mimeType))
1329         return true;
1330
1331 #if ENABLE(NETSCAPE_PLUGIN_API)
1332     String newMimeType = mimeType;
1333     PluginModuleInfo plugin = m_process->processPool().pluginInfoStore().findPlugin(newMimeType, URL());
1334     if (!plugin.path.isNull() && m_preferences->pluginsEnabled())
1335         return true;
1336 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1337
1338 #if PLATFORM(COCOA)
1339     // On Mac, we can show PDFs.
1340     if (MIMETypeRegistry::isPDFOrPostScriptMIMEType(mimeType) && !WebProcessPool::omitPDFSupport())
1341         return true;
1342 #endif // PLATFORM(COCOA)
1343
1344     return false;
1345 }
1346
1347 void WebPageProxy::setControlledByAutomation(bool controlled)
1348 {
1349     if (m_controlledByAutomation == controlled)
1350         return;
1351
1352     m_controlledByAutomation = controlled;
1353
1354     if (isValid())
1355         m_process->send(Messages::WebPage::SetControlledByAutomation(controlled), m_pageID);
1356 }
1357
1358 #if ENABLE(REMOTE_INSPECTOR)
1359 void WebPageProxy::setAllowsRemoteInspection(bool allow)
1360 {
1361     if (m_allowsRemoteInspection == allow)
1362         return;
1363
1364     m_allowsRemoteInspection = allow;
1365
1366     if (isValid())
1367         m_process->send(Messages::WebPage::SetAllowsRemoteInspection(allow), m_pageID);
1368 }
1369
1370 void WebPageProxy::setRemoteInspectionNameOverride(const String& name)
1371 {
1372     if (m_remoteInspectionNameOverride == name)
1373         return;
1374
1375     m_remoteInspectionNameOverride = name;
1376
1377     if (isValid())
1378         m_process->send(Messages::WebPage::SetRemoteInspectionNameOverride(m_remoteInspectionNameOverride), m_pageID);
1379 }
1380
1381 #endif
1382
1383 void WebPageProxy::setDrawsBackground(bool drawsBackground)
1384 {
1385     if (m_drawsBackground == drawsBackground)
1386         return;
1387
1388     m_drawsBackground = drawsBackground;
1389
1390     if (isValid())
1391         m_process->send(Messages::WebPage::SetDrawsBackground(drawsBackground), m_pageID);
1392 }
1393
1394 void WebPageProxy::setTopContentInset(float contentInset)
1395 {
1396     if (m_topContentInset == contentInset)
1397         return;
1398
1399     m_topContentInset = contentInset;
1400
1401     if (!isValid())
1402         return;
1403 #if PLATFORM(COCOA)
1404     MachSendRight fence = m_drawingArea->createFence();
1405
1406     auto fenceAttachment = IPC::Attachment(fence.leakSendRight(), MACH_MSG_TYPE_MOVE_SEND);
1407     m_process->send(Messages::WebPage::SetTopContentInsetFenced(contentInset, fenceAttachment), m_pageID);
1408 #else
1409     m_process->send(Messages::WebPage::SetTopContentInset(contentInset), m_pageID);
1410 #endif
1411 }
1412
1413 void WebPageProxy::setUnderlayColor(const Color& color)
1414 {
1415     if (m_underlayColor == color)
1416         return;
1417
1418     m_underlayColor = color;
1419
1420     if (isValid())
1421         m_process->send(Messages::WebPage::SetUnderlayColor(color), m_pageID);
1422 }
1423
1424 void WebPageProxy::viewWillStartLiveResize()
1425 {
1426     if (!isValid())
1427         return;
1428 #if ENABLE(INPUT_TYPE_COLOR_POPOVER) && ENABLE(INPUT_TYPE_COLOR)
1429     if (m_colorPicker)
1430         endColorPicker();
1431 #endif
1432     m_process->send(Messages::WebPage::ViewWillStartLiveResize(), m_pageID);
1433 }
1434
1435 void WebPageProxy::viewWillEndLiveResize()
1436 {
1437     if (!isValid())
1438         return;
1439     m_process->send(Messages::WebPage::ViewWillEndLiveResize(), m_pageID);
1440 }
1441
1442 void WebPageProxy::setViewNeedsDisplay(const Region& region)
1443 {
1444     m_pageClient.setViewNeedsDisplay(region);
1445 }
1446
1447 void WebPageProxy::requestScroll(const FloatPoint& scrollPosition, const IntPoint& scrollOrigin, bool isProgrammaticScroll)
1448 {
1449     m_pageClient.requestScroll(scrollPosition, scrollOrigin, isProgrammaticScroll);
1450 }
1451
1452 void WebPageProxy::setSuppressVisibilityUpdates(bool flag)
1453 {
1454     if (m_suppressVisibilityUpdates == flag)
1455         return;
1456     m_suppressVisibilityUpdates = flag;
1457
1458     if (!m_suppressVisibilityUpdates) {
1459 #if PLATFORM(COCOA)
1460         m_activityStateChangeDispatcher->schedule();
1461 #else
1462         dispatchActivityStateChange();
1463 #endif
1464     }
1465 }
1466
1467 void WebPageProxy::updateActivityState(ActivityState::Flags flagsToUpdate)
1468 {
1469     m_activityState &= ~flagsToUpdate;
1470     if (flagsToUpdate & ActivityState::IsFocused && m_pageClient.isViewFocused())
1471         m_activityState |= ActivityState::IsFocused;
1472     if (flagsToUpdate & ActivityState::WindowIsActive && m_pageClient.isViewWindowActive())
1473         m_activityState |= ActivityState::WindowIsActive;
1474     if (flagsToUpdate & ActivityState::IsVisible && m_pageClient.isViewVisible())
1475         m_activityState |= ActivityState::IsVisible;
1476     if (flagsToUpdate & ActivityState::IsVisibleOrOccluded && m_pageClient.isViewVisibleOrOccluded())
1477         m_activityState |= ActivityState::IsVisibleOrOccluded;
1478     if (flagsToUpdate & ActivityState::IsInWindow && m_pageClient.isViewInWindow())
1479         m_activityState |= ActivityState::IsInWindow;
1480     if (flagsToUpdate & ActivityState::IsVisuallyIdle && m_pageClient.isVisuallyIdle())
1481         m_activityState |= ActivityState::IsVisuallyIdle;
1482     if (flagsToUpdate & ActivityState::IsAudible && m_mediaState & MediaProducer::IsPlayingAudio && !(m_mutedState & MediaProducer::AudioIsMuted))
1483         m_activityState |= ActivityState::IsAudible;
1484     if (flagsToUpdate & ActivityState::IsLoading && m_pageLoadState.isLoading())
1485         m_activityState |= ActivityState::IsLoading;
1486 }
1487
1488 void WebPageProxy::activityStateDidChange(ActivityState::Flags mayHaveChanged, bool wantsSynchronousReply, ActivityStateChangeDispatchMode dispatchMode)
1489 {
1490     m_potentiallyChangedActivityStateFlags |= mayHaveChanged;
1491     m_activityStateChangeWantsSynchronousReply = m_activityStateChangeWantsSynchronousReply || wantsSynchronousReply;
1492
1493     if (m_suppressVisibilityUpdates && dispatchMode != ActivityStateChangeDispatchMode::Immediate)
1494         return;
1495
1496 #if PLATFORM(COCOA)
1497     bool isNewlyInWindow = !isInWindow() && (mayHaveChanged & ActivityState::IsInWindow) && m_pageClient.isViewInWindow();
1498     if (dispatchMode == ActivityStateChangeDispatchMode::Immediate || isNewlyInWindow) {
1499         dispatchActivityStateChange();
1500         return;
1501     }
1502     m_activityStateChangeDispatcher->schedule();
1503 #else
1504     UNUSED_PARAM(dispatchMode);
1505     dispatchActivityStateChange();
1506 #endif
1507 }
1508
1509 void WebPageProxy::viewDidLeaveWindow()
1510 {
1511 #if ENABLE(INPUT_TYPE_COLOR_POPOVER) && ENABLE(INPUT_TYPE_COLOR)
1512     // When leaving the current page, close the popover color well.
1513     if (m_colorPicker)
1514         endColorPicker();
1515 #endif
1516 #if PLATFORM(IOS) && HAVE(AVKIT) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
1517     // When leaving the current page, close the video fullscreen.
1518     if (m_videoFullscreenManager)
1519         m_videoFullscreenManager->requestHideAndExitFullscreen();
1520 #endif
1521 }
1522
1523 void WebPageProxy::viewDidEnterWindow()
1524 {
1525     LayerHostingMode layerHostingMode = m_pageClient.viewLayerHostingMode();
1526     if (m_layerHostingMode != layerHostingMode) {
1527         m_layerHostingMode = layerHostingMode;
1528         m_process->send(Messages::WebPage::SetLayerHostingMode(layerHostingMode), m_pageID);
1529     }
1530 }
1531
1532 void WebPageProxy::dispatchActivityStateChange()
1533 {
1534 #if PLATFORM(COCOA)
1535     m_activityStateChangeDispatcher->invalidate();
1536 #endif
1537
1538     if (!isValid())
1539         return;
1540
1541     // If the visibility state may have changed, then so may the visually idle & occluded agnostic state.
1542     if (m_potentiallyChangedActivityStateFlags & ActivityState::IsVisible)
1543         m_potentiallyChangedActivityStateFlags |= ActivityState::IsVisibleOrOccluded | ActivityState::IsVisuallyIdle;
1544
1545     // Record the prior view state, update the flags that may have changed,
1546     // and check which flags have actually changed.
1547     ActivityState::Flags previousActivityState = m_activityState;
1548     updateActivityState(m_potentiallyChangedActivityStateFlags);
1549     ActivityState::Flags changed = m_activityState ^ previousActivityState;
1550
1551     bool isNowInWindow = (changed & ActivityState::IsInWindow) && isInWindow();
1552     // We always want to wait for the Web process to reply if we've been in-window before and are coming back in-window.
1553     if (m_viewWasEverInWindow && isNowInWindow && m_drawingArea->hasVisibleContent() && m_waitsForPaintAfterViewDidMoveToWindow)
1554         m_activityStateChangeWantsSynchronousReply = true;
1555
1556     // Don't wait synchronously if the view state is not visible. (This matters in particular on iOS, where a hidden page may be suspended.)
1557     if (!(m_activityState & ActivityState::IsVisible))
1558         m_activityStateChangeWantsSynchronousReply = false;
1559
1560     if (changed || m_activityStateChangeWantsSynchronousReply || !m_nextActivityStateChangeCallbacks.isEmpty())
1561         m_process->send(Messages::WebPage::SetActivityState(m_activityState, m_activityStateChangeWantsSynchronousReply, m_nextActivityStateChangeCallbacks), m_pageID);
1562
1563     m_nextActivityStateChangeCallbacks.clear();
1564
1565     // This must happen after the SetActivityState message is sent, to ensure the page visibility event can fire.
1566     updateThrottleState();
1567
1568     // If we've started the responsiveness timer as part of telling the web process to update the backing store
1569     // state, it might not send back a reply (since it won't paint anything if the web page is hidden) so we
1570     // stop the unresponsiveness timer here.
1571     if ((changed & ActivityState::IsVisible) && !isViewVisible())
1572         m_process->responsivenessTimer().stop();
1573
1574 #if ENABLE(POINTER_LOCK)
1575     if (((changed & ActivityState::IsVisible) && !isViewVisible()) || ((changed & ActivityState::WindowIsActive) && !m_pageClient.isViewWindowActive()))
1576         requestPointerUnlock();
1577 #endif
1578
1579     if (changed & ActivityState::IsInWindow) {
1580         if (isInWindow())
1581             viewDidEnterWindow();
1582         else
1583             viewDidLeaveWindow();
1584     }
1585
1586     updateBackingStoreDiscardableState();
1587
1588     if (m_activityStateChangeWantsSynchronousReply)
1589         waitForDidUpdateActivityState();
1590
1591     m_potentiallyChangedActivityStateFlags = ActivityState::NoFlags;
1592     m_activityStateChangeWantsSynchronousReply = false;
1593     m_viewWasEverInWindow |= isNowInWindow;
1594 }
1595
1596 bool WebPageProxy::isAlwaysOnLoggingAllowed() const
1597 {
1598     return sessionID().isAlwaysOnLoggingAllowed();
1599 }
1600
1601 void WebPageProxy::updateThrottleState()
1602 {
1603     bool processSuppressionEnabled = m_preferences->pageVisibilityBasedProcessSuppressionEnabled();
1604
1605     // If process suppression is not enabled take a token on the process pool to disable suppression of support processes.
1606     if (!processSuppressionEnabled)
1607         m_preventProcessSuppressionCount = m_process->processPool().processSuppressionDisabledForPageCount();
1608     else if (!m_preventProcessSuppressionCount)
1609         m_preventProcessSuppressionCount = nullptr;
1610
1611     if (m_activityState & ActivityState::IsVisuallyIdle)
1612         m_pageIsUserObservableCount = nullptr;
1613     else if (!m_pageIsUserObservableCount)
1614         m_pageIsUserObservableCount = m_process->processPool().userObservablePageCount();
1615
1616 #if PLATFORM(IOS)
1617     if (!isViewVisible() && !m_alwaysRunsAtForegroundPriority) {
1618         if (m_activityToken) {
1619             RELEASE_LOG_IF_ALLOWED("%p - UIProcess is releasing a foreground assertion because the view is no longer visible", this);
1620             m_activityToken = nullptr;
1621         }
1622     } else if (!m_activityToken) {
1623         if (isViewVisible())
1624             RELEASE_LOG_IF_ALLOWED("%p - UIProcess is taking a foreground assertion because the view is visible", this);
1625         else
1626             RELEASE_LOG_IF_ALLOWED("%p - UIProcess is taking a foreground assertion even though the view is not visible because m_alwaysRunsAtForegroundPriority is true", this);
1627         m_activityToken = m_process->throttler().foregroundActivityToken();
1628     }
1629 #endif
1630 }
1631
1632 void WebPageProxy::updateHiddenPageThrottlingAutoIncreases()
1633 {
1634     if (!m_preferences->hiddenPageDOMTimerThrottlingAutoIncreases())
1635         m_hiddenPageDOMTimerThrottlingAutoIncreasesCount = nullptr;
1636     else if (!m_hiddenPageDOMTimerThrottlingAutoIncreasesCount)
1637         m_hiddenPageDOMTimerThrottlingAutoIncreasesCount = m_process->processPool().hiddenPageThrottlingAutoIncreasesCount();
1638 }
1639
1640 void WebPageProxy::layerHostingModeDidChange()
1641 {
1642     if (!isValid())
1643         return;
1644
1645     LayerHostingMode layerHostingMode = m_pageClient.viewLayerHostingMode();
1646     if (m_layerHostingMode == layerHostingMode)
1647         return;
1648
1649     m_layerHostingMode = layerHostingMode;
1650     m_process->send(Messages::WebPage::SetLayerHostingMode(layerHostingMode), m_pageID);
1651 }
1652
1653 void WebPageProxy::waitForDidUpdateActivityState()
1654 {
1655     if (!isValid())
1656         return;
1657
1658     if (m_process->state() != WebProcessProxy::State::Running)
1659         return;
1660
1661     // If we have previously timed out with no response from the WebProcess, don't block the UIProcess again until it starts responding.
1662     if (m_waitingForDidUpdateActivityState)
1663         return;
1664
1665 #if PLATFORM(IOS)
1666     // Hail Mary check. Should not be possible (dispatchActivityStateChange should force async if not visible,
1667     // and if visible we should be holding an assertion) - but we should never block on a suspended process.
1668     if (!m_activityToken) {
1669         ASSERT_NOT_REACHED();
1670         return;
1671     }
1672 #endif
1673
1674     m_waitingForDidUpdateActivityState = true;
1675
1676     m_drawingArea->waitForDidUpdateActivityState();
1677 }
1678
1679 IntSize WebPageProxy::viewSize() const
1680 {
1681     return m_pageClient.viewSize();
1682 }
1683
1684 void WebPageProxy::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& keyboardEvent, std::function<void (CallbackBase::Error)> callbackFunction)
1685 {
1686     if (!isValid()) {
1687         callbackFunction(CallbackBase::Error::OwnerWasInvalidated);
1688         return;
1689     }
1690
1691     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
1692     m_process->send(Messages::WebPage::SetInitialFocus(forward, isKeyboardEventValid, keyboardEvent, callbackID), m_pageID);
1693 }
1694
1695 void WebPageProxy::clearSelection()
1696 {
1697     if (!isValid())
1698         return;
1699     m_process->send(Messages::WebPage::ClearSelection(), m_pageID);
1700 }
1701
1702 void WebPageProxy::restoreSelectionInFocusedEditableElement()
1703 {
1704     if (!isValid())
1705         return;
1706     m_process->send(Messages::WebPage::RestoreSelectionInFocusedEditableElement(), m_pageID);
1707 }
1708
1709 void WebPageProxy::validateCommand(const String& commandName, std::function<void (const String&, bool, int32_t, CallbackBase::Error)> callbackFunction)
1710 {
1711     if (!isValid()) {
1712         callbackFunction(String(), false, 0, CallbackBase::Error::Unknown);
1713         return;
1714     }
1715
1716     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
1717     m_process->send(Messages::WebPage::ValidateCommand(commandName, callbackID), m_pageID);
1718 }
1719
1720 void WebPageProxy::setMaintainsInactiveSelection(bool newValue)
1721 {
1722     m_maintainsInactiveSelection = newValue;
1723 }
1724     
1725 void WebPageProxy::executeEditCommand(const String& commandName, const String& argument)
1726 {
1727     static NeverDestroyed<String> ignoreSpellingCommandName(ASCIILiteral("ignoreSpelling"));
1728
1729     if (!isValid())
1730         return;
1731
1732     if (commandName == ignoreSpellingCommandName)
1733         ++m_pendingLearnOrIgnoreWordMessageCount;
1734
1735     m_process->send(Messages::WebPage::ExecuteEditCommand(commandName, argument), m_pageID);
1736 }
1737
1738 void WebPageProxy::setEditable(bool editable)
1739 {
1740     if (editable == m_isEditable)
1741         return;
1742     if (!isValid())
1743         return;
1744
1745     m_isEditable = editable;
1746     m_process->send(Messages::WebPage::SetEditable(editable), m_pageID);
1747 }
1748
1749 #if !PLATFORM(IOS)
1750 void WebPageProxy::didCommitLayerTree(const RemoteLayerTreeTransaction&)
1751 {
1752 }
1753
1754 void WebPageProxy::layerTreeCommitComplete()
1755 {
1756 }
1757 #endif
1758
1759 #if ENABLE(DRAG_SUPPORT)
1760 void WebPageProxy::dragEntered(DragData& dragData, const String& dragStorageName)
1761 {
1762     SandboxExtension::Handle sandboxExtensionHandle;
1763     SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray;
1764     performDragControllerAction(DragControllerActionEntered, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray);
1765 }
1766
1767 void WebPageProxy::dragUpdated(DragData& dragData, const String& dragStorageName)
1768 {
1769     SandboxExtension::Handle sandboxExtensionHandle;
1770     SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray;
1771     performDragControllerAction(DragControllerActionUpdated, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray);
1772 }
1773
1774 void WebPageProxy::dragExited(DragData& dragData, const String& dragStorageName)
1775 {
1776     SandboxExtension::Handle sandboxExtensionHandle;
1777     SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray;
1778     performDragControllerAction(DragControllerActionExited, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray);
1779 }
1780
1781 void WebPageProxy::performDragOperation(DragData& dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload)
1782 {
1783     performDragControllerAction(DragControllerActionPerformDragOperation, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionsForUpload);
1784 }
1785
1786 void WebPageProxy::performDragControllerAction(DragControllerAction action, DragData& dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload)
1787 {
1788     if (!isValid())
1789         return;
1790 #if PLATFORM(GTK)
1791     UNUSED_PARAM(dragStorageName);
1792     UNUSED_PARAM(sandboxExtensionHandle);
1793     UNUSED_PARAM(sandboxExtensionsForUpload);
1794
1795     String url = dragData.asURL();
1796     if (!url.isEmpty())
1797         m_process->assumeReadAccessToBaseURL(url);
1798
1799     ASSERT(dragData.platformData());
1800     WebSelectionData selection(*dragData.platformData());
1801     m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData.clientPosition(), dragData.globalPosition(), dragData.draggingSourceOperationMask(), selection, dragData.flags()), m_pageID);
1802 #else
1803     m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData, sandboxExtensionHandle, sandboxExtensionsForUpload), m_pageID);
1804 #endif
1805 }
1806
1807 void WebPageProxy::didPerformDragControllerAction(uint64_t dragOperation, bool mouseIsOverFileInput, unsigned numberOfItemsToBeAccepted)
1808 {
1809     MESSAGE_CHECK(dragOperation <= DragOperationDelete);
1810
1811     m_currentDragOperation = static_cast<DragOperation>(dragOperation);
1812     m_currentDragIsOverFileInput = mouseIsOverFileInput;
1813     m_currentDragNumberOfFilesToBeAccepted = numberOfItemsToBeAccepted;
1814 }
1815
1816 #if PLATFORM(GTK)
1817 void WebPageProxy::startDrag(WebSelectionData&& selection, uint64_t dragOperation, const ShareableBitmap::Handle& dragImageHandle)
1818 {
1819     RefPtr<ShareableBitmap> dragImage = !dragImageHandle.isNull() ? ShareableBitmap::create(dragImageHandle) : nullptr;
1820     m_pageClient.startDrag(WTFMove(selection.selectionData), static_cast<WebCore::DragOperation>(dragOperation), WTFMove(dragImage));
1821
1822     m_process->send(Messages::WebPage::DidStartDrag(), m_pageID);
1823 }
1824 #endif
1825
1826 void WebPageProxy::dragEnded(const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t operation)
1827 {
1828     if (!isValid())
1829         return;
1830     m_process->send(Messages::WebPage::DragEnded(clientPosition, globalPosition, operation), m_pageID);
1831 }
1832 #endif // ENABLE(DRAG_SUPPORT)
1833
1834 void WebPageProxy::handleMouseEvent(const NativeWebMouseEvent& event)
1835 {
1836     if (!isValid())
1837         return;
1838
1839     if (m_pageClient.windowIsFrontWindowUnderMouse(event))
1840         setToolTip(String());
1841
1842     // NOTE: This does not start the responsiveness timer because mouse move should not indicate interaction.
1843     if (event.type() != WebEvent::MouseMove)
1844         m_process->responsivenessTimer().start();
1845     else {
1846         if (m_processingMouseMoveEvent) {
1847             m_nextMouseMoveEvent = std::make_unique<NativeWebMouseEvent>(event);
1848             return;
1849         }
1850
1851         m_processingMouseMoveEvent = true;
1852     }
1853
1854     // <https://bugs.webkit.org/show_bug.cgi?id=57904> We need to keep track of the mouse down event in the case where we
1855     // display a popup menu for select elements. When the user changes the selected item,
1856     // we fake a mouse up event by using this stored down event. This event gets cleared
1857     // when the mouse up message is received from WebProcess.
1858     if (event.type() == WebEvent::MouseDown)
1859         m_currentlyProcessedMouseDownEvent = std::make_unique<NativeWebMouseEvent>(event);
1860
1861     m_process->send(Messages::WebPage::MouseEvent(event), m_pageID);
1862 }
1863
1864 #if MERGE_WHEEL_EVENTS
1865 static bool canCoalesce(const WebWheelEvent& a, const WebWheelEvent& b)
1866 {
1867     if (a.position() != b.position())
1868         return false;
1869     if (a.globalPosition() != b.globalPosition())
1870         return false;
1871     if (a.modifiers() != b.modifiers())
1872         return false;
1873     if (a.granularity() != b.granularity())
1874         return false;
1875 #if PLATFORM(COCOA)
1876     if (a.phase() != b.phase())
1877         return false;
1878     if (a.momentumPhase() != b.momentumPhase())
1879         return false;
1880     if (a.hasPreciseScrollingDeltas() != b.hasPreciseScrollingDeltas())
1881         return false;
1882 #endif
1883
1884     return true;
1885 }
1886
1887 static WebWheelEvent coalesce(const WebWheelEvent& a, const WebWheelEvent& b)
1888 {
1889     ASSERT(canCoalesce(a, b));
1890
1891     FloatSize mergedDelta = a.delta() + b.delta();
1892     FloatSize mergedWheelTicks = a.wheelTicks() + b.wheelTicks();
1893
1894 #if PLATFORM(COCOA)
1895     FloatSize mergedUnacceleratedScrollingDelta = a.unacceleratedScrollingDelta() + b.unacceleratedScrollingDelta();
1896
1897     return WebWheelEvent(WebEvent::Wheel, b.position(), b.globalPosition(), mergedDelta, mergedWheelTicks, b.granularity(), b.directionInvertedFromDevice(), b.phase(), b.momentumPhase(), b.hasPreciseScrollingDeltas(), b.scrollCount(), mergedUnacceleratedScrollingDelta, b.modifiers(), b.timestamp());
1898 #else
1899     return WebWheelEvent(WebEvent::Wheel, b.position(), b.globalPosition(), mergedDelta, mergedWheelTicks, b.granularity(), b.modifiers(), b.timestamp());
1900 #endif
1901 }
1902 #endif // MERGE_WHEEL_EVENTS
1903
1904 static WebWheelEvent coalescedWheelEvent(Deque<NativeWebWheelEvent>& queue, Vector<NativeWebWheelEvent>& coalescedEvents)
1905 {
1906     ASSERT(!queue.isEmpty());
1907     ASSERT(coalescedEvents.isEmpty());
1908
1909 #if MERGE_WHEEL_EVENTS
1910     NativeWebWheelEvent firstEvent = queue.takeFirst();
1911     coalescedEvents.append(firstEvent);
1912
1913     WebWheelEvent event = firstEvent;
1914     while (!queue.isEmpty() && canCoalesce(event, queue.first())) {
1915         NativeWebWheelEvent firstEvent = queue.takeFirst();
1916         coalescedEvents.append(firstEvent);
1917         event = coalesce(event, firstEvent);
1918     }
1919
1920     return event;
1921 #else
1922     while (!queue.isEmpty())
1923         coalescedEvents.append(queue.takeFirst());
1924     return coalescedEvents.last();
1925 #endif
1926 }
1927
1928 void WebPageProxy::handleWheelEvent(const NativeWebWheelEvent& event)
1929 {
1930 #if ENABLE(ASYNC_SCROLLING)
1931     if (m_scrollingCoordinatorProxy && m_scrollingCoordinatorProxy->handleWheelEvent(platform(event)))
1932         return;
1933 #endif
1934
1935     if (!isValid())
1936         return;
1937
1938     hideValidationMessage();
1939
1940     if (!m_currentlyProcessedWheelEvents.isEmpty()) {
1941         m_wheelEventQueue.append(event);
1942         if (m_wheelEventQueue.size() < wheelEventQueueSizeThreshold)
1943             return;
1944         // The queue has too many wheel events, so push a new event.
1945     }
1946
1947     if (!m_wheelEventQueue.isEmpty()) {
1948         processNextQueuedWheelEvent();
1949         return;
1950     }
1951
1952     auto coalescedWheelEvent = std::make_unique<Vector<NativeWebWheelEvent>>();
1953     coalescedWheelEvent->append(event);
1954     m_currentlyProcessedWheelEvents.append(WTFMove(coalescedWheelEvent));
1955     sendWheelEvent(event);
1956 }
1957
1958 void WebPageProxy::processNextQueuedWheelEvent()
1959 {
1960     auto nextCoalescedEvent = std::make_unique<Vector<NativeWebWheelEvent>>();
1961     WebWheelEvent nextWheelEvent = coalescedWheelEvent(m_wheelEventQueue, *nextCoalescedEvent.get());
1962     m_currentlyProcessedWheelEvents.append(WTFMove(nextCoalescedEvent));
1963     sendWheelEvent(nextWheelEvent);
1964 }
1965
1966 void WebPageProxy::sendWheelEvent(const WebWheelEvent& event)
1967 {
1968     m_process->send(
1969         Messages::EventDispatcher::WheelEvent(
1970             m_pageID,
1971             event,
1972             shouldUseImplicitRubberBandControl() ? !m_backForwardList->backItem() : rubberBandsAtLeft(),
1973             shouldUseImplicitRubberBandControl() ? !m_backForwardList->forwardItem() : rubberBandsAtRight(),
1974             rubberBandsAtTop(),
1975             rubberBandsAtBottom()
1976         ), 0);
1977
1978     // Manually ping the web process to check for responsiveness since our wheel
1979     // event will dispatch to a non-main thread, which always responds.
1980     m_process->isResponsive(nullptr);
1981 }
1982
1983 void WebPageProxy::handleKeyboardEvent(const NativeWebKeyboardEvent& event)
1984 {
1985     if (!isValid())
1986         return;
1987     
1988     LOG(KeyHandling, "WebPageProxy::handleKeyboardEvent: %s", webKeyboardEventTypeString(event.type()));
1989
1990     m_keyEventQueue.append(event);
1991
1992     m_process->responsivenessTimer().start();
1993     if (m_keyEventQueue.size() == 1) { // Otherwise, sent from DidReceiveEvent message handler.
1994         LOG(KeyHandling, " UI process: sent keyEvent from handleKeyboardEvent");
1995         m_process->send(Messages::WebPage::KeyEvent(event), m_pageID);
1996     }
1997 }
1998
1999 WebPreferencesStore WebPageProxy::preferencesStore() const
2000 {
2001     if (m_configurationPreferenceValues.isEmpty())
2002         return m_preferences->store();
2003
2004     WebPreferencesStore store = m_preferences->store();
2005     for (const auto& preference : m_configurationPreferenceValues)
2006         store.m_values.set(preference.key, preference.value);
2007
2008     return store;
2009 }
2010
2011 #if ENABLE(NETSCAPE_PLUGIN_API)
2012 void WebPageProxy::findPlugin(const String& mimeType, uint32_t processType, const String& urlString, const String& frameURLString, const String& pageURLString, bool allowOnlyApplicationPlugins, uint64_t& pluginProcessToken, String& newMimeType, uint32_t& pluginLoadPolicy, String& unavailabilityDescription)
2013 {
2014     PageClientProtector protector(m_pageClient);
2015
2016     MESSAGE_CHECK_URL(urlString);
2017
2018     newMimeType = mimeType.convertToASCIILowercase();
2019     pluginLoadPolicy = PluginModuleLoadNormally;
2020
2021     PluginData::AllowedPluginTypes allowedPluginTypes = allowOnlyApplicationPlugins ? PluginData::OnlyApplicationPlugins : PluginData::AllPlugins;
2022     PluginModuleInfo plugin = m_process->processPool().pluginInfoStore().findPlugin(newMimeType, URL(URL(), urlString), allowedPluginTypes);
2023     if (!plugin.path) {
2024         pluginProcessToken = 0;
2025         return;
2026     }
2027
2028     pluginLoadPolicy = PluginInfoStore::defaultLoadPolicyForPlugin(plugin);
2029
2030 #if PLATFORM(COCOA)
2031     RefPtr<API::Dictionary> pluginInformation = createPluginInformationDictionary(plugin, frameURLString, String(), pageURLString, String(), String());
2032     if (m_navigationClient)
2033         pluginLoadPolicy = m_navigationClient->decidePolicyForPluginLoad(*this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get(), unavailabilityDescription);
2034     else
2035         pluginLoadPolicy = m_loaderClient->pluginLoadPolicy(*this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get(), unavailabilityDescription);
2036 #else
2037     UNUSED_PARAM(frameURLString);
2038     UNUSED_PARAM(pageURLString);
2039     UNUSED_PARAM(unavailabilityDescription);
2040 #endif
2041
2042     PluginProcessSandboxPolicy pluginProcessSandboxPolicy = PluginProcessSandboxPolicyNormal;
2043     switch (pluginLoadPolicy) {
2044     case PluginModuleLoadNormally:
2045         pluginProcessSandboxPolicy = PluginProcessSandboxPolicyNormal;
2046         break;
2047     case PluginModuleLoadUnsandboxed:
2048         pluginProcessSandboxPolicy = PluginProcessSandboxPolicyUnsandboxed;
2049         break;
2050
2051     case PluginModuleBlockedForSecurity:
2052     case PluginModuleBlockedForCompatibility:
2053         pluginProcessToken = 0;
2054         return;
2055     }
2056
2057     pluginProcessToken = PluginProcessManager::singleton().pluginProcessToken(plugin, static_cast<PluginProcessType>(processType), pluginProcessSandboxPolicy);
2058 }
2059
2060 #endif // ENABLE(NETSCAPE_PLUGIN_API)
2061
2062 #if ENABLE(TOUCH_EVENTS)
2063
2064 static TrackingType mergeTrackingTypes(TrackingType a, TrackingType b)
2065 {
2066     if (static_cast<uintptr_t>(b) > static_cast<uintptr_t>(a))
2067         return b;
2068     return a;
2069 }
2070
2071 void WebPageProxy::updateTouchEventTracking(const WebTouchEvent& touchStartEvent)
2072 {
2073 #if ENABLE(ASYNC_SCROLLING)
2074     const EventNames& names = eventNames();
2075     for (auto& touchPoint : touchStartEvent.touchPoints()) {
2076         IntPoint location = touchPoint.location();
2077         auto updateTrackingType = [this, location](TrackingType& trackingType, const AtomicString& eventName) {
2078             if (trackingType == TrackingType::Synchronous)
2079                 return;
2080
2081             TrackingType trackingTypeForLocation = m_scrollingCoordinatorProxy->eventTrackingTypeForPoint(eventName, location);
2082
2083             trackingType = mergeTrackingTypes(trackingType, trackingTypeForLocation);
2084         };
2085         updateTrackingType(m_touchEventTracking.touchForceChangedTracking, names.touchforcechangeEvent);
2086         updateTrackingType(m_touchEventTracking.touchStartTracking, names.touchstartEvent);
2087         updateTrackingType(m_touchEventTracking.touchMoveTracking, names.touchmoveEvent);
2088         updateTrackingType(m_touchEventTracking.touchEndTracking, names.touchendEvent);
2089     }
2090 #else
2091     UNUSED_PARAM(touchStartEvent);
2092     m_touchEventTracking.touchForceChangedTracking = TrackingType::Synchronous;
2093     m_touchEventTracking.touchStartTracking = TrackingType::Synchronous;
2094     m_touchEventTracking.touchMoveTracking = TrackingType::Synchronous;
2095     m_touchEventTracking.touchEndTracking = TrackingType::Synchronous;
2096 #endif // ENABLE(ASYNC_SCROLLING)
2097 }
2098
2099 TrackingType WebPageProxy::touchEventTrackingType(const WebTouchEvent& touchStartEvent) const
2100 {
2101     // We send all events if any type is needed, we just do it asynchronously for the types that are not tracked.
2102     //
2103     // Touch events define a sequence with strong dependencies. For example, we can expect
2104     // a TouchMove to only appear after a TouchStart, and the ids of the touch points is consistent between
2105     // the two.
2106     //
2107     // WebCore should not have to set up its state correctly after some events were dismissed.
2108     // For example, we don't want to send a TouchMoved without a TouchPressed.
2109     // We send everything, WebCore updates its internal state and dispatch what is needed to the page.
2110     TrackingType globalTrackingType = m_touchEventTracking.isTrackingAnything() ? TrackingType::Asynchronous : TrackingType::NotTracking;
2111
2112     globalTrackingType = mergeTrackingTypes(globalTrackingType, m_touchEventTracking.touchForceChangedTracking);
2113     for (auto& touchPoint : touchStartEvent.touchPoints()) {
2114         switch (touchPoint.state()) {
2115         case WebPlatformTouchPoint::TouchReleased:
2116             globalTrackingType = mergeTrackingTypes(globalTrackingType, m_touchEventTracking.touchEndTracking);
2117             break;
2118         case WebPlatformTouchPoint::TouchPressed:
2119             globalTrackingType = mergeTrackingTypes(globalTrackingType, m_touchEventTracking.touchStartTracking);
2120             break;
2121         case WebPlatformTouchPoint::TouchMoved:
2122         case WebPlatformTouchPoint::TouchStationary:
2123             globalTrackingType = mergeTrackingTypes(globalTrackingType, m_touchEventTracking.touchMoveTracking);
2124             break;
2125         case WebPlatformTouchPoint::TouchCancelled:
2126             globalTrackingType = mergeTrackingTypes(globalTrackingType, TrackingType::Asynchronous);
2127             break;
2128         }
2129     }
2130
2131     return globalTrackingType;
2132 }
2133
2134 #endif
2135
2136 #if ENABLE(MAC_GESTURE_EVENTS)
2137 void WebPageProxy::handleGestureEvent(const NativeWebGestureEvent& event)
2138 {
2139     if (!isValid())
2140         return;
2141
2142     m_gestureEventQueue.append(event);
2143     // FIXME: Consider doing some coalescing here.
2144     m_process->responsivenessTimer().start();
2145
2146     m_process->send(Messages::EventDispatcher::GestureEvent(m_pageID, event), 0);
2147 }
2148 #endif
2149
2150 #if ENABLE(IOS_TOUCH_EVENTS)
2151 void WebPageProxy::handleTouchEventSynchronously(NativeWebTouchEvent& event)
2152 {
2153     if (!isValid())
2154         return;
2155
2156     if (event.type() == WebEvent::TouchStart) {
2157         updateTouchEventTracking(event);
2158         m_layerTreeTransactionIdAtLastTouchStart = downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea()).lastCommittedLayerTreeTransactionID();
2159     }
2160
2161     TrackingType touchEventsTrackingType = touchEventTrackingType(event);
2162     if (touchEventsTrackingType == TrackingType::NotTracking)
2163         return;
2164
2165     if (touchEventsTrackingType == TrackingType::Asynchronous) {
2166         // We can end up here if a native gesture has not started but the event handlers are passive.
2167         //
2168         // The client of WebPageProxy asks the event to be sent synchronously since the touch event
2169         // can prevent a native gesture.
2170         // But, here we know that all events handlers that can handle this events are passive.
2171         // We can use asynchronous dispatch and pretend to the client that the page does nothing with the events.
2172         event.setCanPreventNativeGestures(false);
2173         handleTouchEventAsynchronously(event);
2174         didReceiveEvent(event.type(), false);
2175         return;
2176     }
2177
2178     m_process->responsivenessTimer().start();
2179     bool handled = false;
2180     m_process->sendSync(Messages::WebPage::TouchEventSync(event), Messages::WebPage::TouchEventSync::Reply(handled), m_pageID);
2181     didReceiveEvent(event.type(), handled);
2182     m_pageClient.doneWithTouchEvent(event, handled);
2183     m_process->responsivenessTimer().stop();
2184
2185     if (event.allTouchPointsAreReleased())
2186         m_touchEventTracking.reset();
2187 }
2188
2189 void WebPageProxy::handleTouchEventAsynchronously(const NativeWebTouchEvent& event)
2190 {
2191     if (!isValid())
2192         return;
2193
2194     TrackingType touchEventsTrackingType = touchEventTrackingType(event);
2195     if (touchEventsTrackingType == TrackingType::NotTracking)
2196         return;
2197
2198     m_process->send(Messages::EventDispatcher::TouchEvent(m_pageID, event), 0);
2199
2200     if (event.allTouchPointsAreReleased())
2201         m_touchEventTracking.reset();
2202 }
2203
2204 #elif ENABLE(TOUCH_EVENTS)
2205 void WebPageProxy::handleTouchEvent(const NativeWebTouchEvent& event)
2206 {
2207     if (!isValid())
2208         return;
2209
2210     if (event.type() == WebEvent::TouchStart)
2211         updateTouchEventTracking(event);
2212
2213     if (touchEventTrackingType(event) == TrackingType::NotTracking)
2214         return;
2215
2216     // If the page is suspended, which should be the case during panning, pinching
2217     // and animation on the page itself (kinetic scrolling, tap to zoom) etc, then
2218     // we do not send any of the events to the page even if is has listeners.
2219     if (!m_isPageSuspended) {
2220         m_touchEventQueue.append(event);
2221         m_process->responsivenessTimer().start();
2222         m_process->send(Messages::WebPage::TouchEvent(event), m_pageID);
2223     } else {
2224         if (m_touchEventQueue.isEmpty()) {
2225             bool isEventHandled = false;
2226             m_pageClient.doneWithTouchEvent(event, isEventHandled);
2227         } else {
2228             // We attach the incoming events to the newest queued event so that all
2229             // the events are delivered in the correct order when the event is dequed.
2230             QueuedTouchEvents& lastEvent = m_touchEventQueue.last();
2231             lastEvent.deferredTouchEvents.append(event);
2232         }
2233     }
2234
2235     if (event.allTouchPointsAreReleased())
2236         m_touchEventTracking.reset();
2237 }
2238 #endif // ENABLE(TOUCH_EVENTS)
2239
2240 void WebPageProxy::scrollBy(ScrollDirection direction, ScrollGranularity granularity)
2241 {
2242     if (!isValid())
2243         return;
2244
2245     m_process->send(Messages::WebPage::ScrollBy(direction, granularity), m_pageID);
2246 }
2247
2248 void WebPageProxy::centerSelectionInVisibleArea()
2249 {
2250     if (!isValid())
2251         return;
2252
2253     m_process->send(Messages::WebPage::CenterSelectionInVisibleArea(), m_pageID);
2254 }
2255
2256 void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy& frame, uint64_t listenerID, API::Navigation* navigation, const WebsitePolicies& websitePolicies)
2257 {
2258     if (!isValid())
2259         return;
2260
2261     auto transaction = m_pageLoadState.transaction();
2262
2263     if (action == PolicyIgnore)
2264         m_pageLoadState.clearPendingAPIRequestURL(transaction);
2265
2266 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2267     if (m_syncNavigationActionHasDownloadAttribute && action == PolicyUse)
2268         action = PolicyDownload;
2269 #endif
2270
2271     DownloadID downloadID = { };
2272     if (action == PolicyDownload) {
2273         // Create a download proxy.
2274         // FIXME: We should ensure that the downloadRequest is never empty.
2275         const ResourceRequest& downloadRequest = m_decidePolicyForResponseRequest ? *m_decidePolicyForResponseRequest : ResourceRequest();
2276         DownloadProxy* download = m_process->processPool().createDownloadProxy(downloadRequest);
2277         downloadID = download->downloadID();
2278         handleDownloadRequest(download);
2279     }
2280
2281     // If we received a policy decision while in decidePolicyForResponse the decision will
2282     // be sent back to the web process by decidePolicyForResponse.
2283     if (m_inDecidePolicyForResponseSync) {
2284         m_syncMimeTypePolicyActionIsValid = true;
2285         m_syncMimeTypePolicyAction = action;
2286         m_syncMimeTypePolicyDownloadID = downloadID;
2287         return;
2288     }
2289
2290     // If we received a policy decision while in decidePolicyForNavigationAction the decision will 
2291     // be sent back to the web process by decidePolicyForNavigationAction. 
2292     if (m_inDecidePolicyForNavigationAction) {
2293         m_syncNavigationActionPolicyActionIsValid = true;
2294         m_syncNavigationActionPolicyAction = action;
2295         m_syncNavigationActionPolicyDownloadID = downloadID;
2296         m_syncNavigationActionPolicyWebsitePolicies = websitePolicies;
2297         return;
2298     }
2299     
2300     m_process->send(Messages::WebPage::DidReceivePolicyDecision(frame.frameID(), listenerID, action, navigation ? navigation->navigationID() : 0, downloadID), m_pageID);
2301 }
2302
2303 void WebPageProxy::setUserAgent(const String& userAgent)
2304 {
2305     if (m_userAgent == userAgent)
2306         return;
2307     m_userAgent = userAgent;
2308
2309     if (!isValid())
2310         return;
2311     m_process->send(Messages::WebPage::SetUserAgent(m_userAgent), m_pageID);
2312 }
2313
2314 void WebPageProxy::setApplicationNameForUserAgent(const String& applicationName)
2315 {
2316     if (m_applicationNameForUserAgent == applicationName)
2317         return;
2318
2319     m_applicationNameForUserAgent = applicationName;
2320     if (!m_customUserAgent.isEmpty())
2321         return;
2322
2323     setUserAgent(standardUserAgent(m_applicationNameForUserAgent));
2324 }
2325
2326 void WebPageProxy::setCustomUserAgent(const String& customUserAgent)
2327 {
2328     if (m_customUserAgent == customUserAgent)
2329         return;
2330
2331     m_customUserAgent = customUserAgent;
2332
2333     if (m_customUserAgent.isEmpty()) {
2334         setUserAgent(standardUserAgent(m_applicationNameForUserAgent));
2335         return;
2336     }
2337
2338     setUserAgent(m_customUserAgent);
2339 }
2340
2341 void WebPageProxy::resumeActiveDOMObjectsAndAnimations()
2342 {
2343     if (!isValid() || !m_isPageSuspended)
2344         return;
2345
2346     m_isPageSuspended = false;
2347
2348     m_process->send(Messages::WebPage::ResumeActiveDOMObjectsAndAnimations(), m_pageID);
2349 }
2350
2351 void WebPageProxy::suspendActiveDOMObjectsAndAnimations()
2352 {
2353     if (!isValid() || m_isPageSuspended)
2354         return;
2355
2356     m_isPageSuspended = true;
2357
2358     m_process->send(Messages::WebPage::SuspendActiveDOMObjectsAndAnimations(), m_pageID);
2359 }
2360
2361 bool WebPageProxy::supportsTextEncoding() const
2362 {
2363     // FIXME (118840): We should probably only support this for text documents, not all non-image documents.
2364     return m_mainFrame && !m_mainFrame->isDisplayingStandaloneImageDocument();
2365 }
2366
2367 void WebPageProxy::setCustomTextEncodingName(const String& encodingName)
2368 {
2369     if (m_customTextEncodingName == encodingName)
2370         return;
2371     m_customTextEncodingName = encodingName;
2372
2373     if (!isValid())
2374         return;
2375     m_process->send(Messages::WebPage::SetCustomTextEncodingName(encodingName), m_pageID);
2376 }
2377
2378 void WebPageProxy::terminateProcess()
2379 {
2380     // NOTE: This uses a check of m_isValid rather than calling isValid() since
2381     // we want this to run even for pages being closed or that already closed.
2382     if (!m_isValid)
2383         return;
2384
2385     m_process->requestTermination();
2386     resetStateAfterProcessExited();
2387 }
2388
2389 SessionState WebPageProxy::sessionState(const std::function<bool (WebBackForwardListItem&)>& filter) const
2390 {
2391     SessionState sessionState;
2392
2393     sessionState.backForwardListState = m_backForwardList->backForwardListState(filter);
2394
2395     String provisionalURLString = m_pageLoadState.pendingAPIRequestURL();
2396     if (provisionalURLString.isEmpty())
2397         provisionalURLString = m_pageLoadState.provisionalURL();
2398
2399     if (!provisionalURLString.isEmpty())
2400         sessionState.provisionalURL = URL(URL(), provisionalURLString);
2401
2402     sessionState.renderTreeSize = renderTreeSize();
2403     return sessionState;
2404 }
2405
2406 RefPtr<API::Navigation> WebPageProxy::restoreFromSessionState(SessionState sessionState, bool navigate)
2407 {
2408     m_sessionRestorationRenderTreeSize = 0;
2409     m_hitRenderTreeSizeThreshold = false;
2410
2411     bool hasBackForwardList = !!sessionState.backForwardListState.currentIndex;
2412
2413     if (hasBackForwardList) {
2414         m_backForwardList->restoreFromState(WTFMove(sessionState.backForwardListState));
2415
2416         for (const auto& entry : m_backForwardList->entries())
2417             process().registerNewWebBackForwardListItem(entry.get());
2418
2419         process().send(Messages::WebPage::RestoreSession(m_backForwardList->itemStates()), m_pageID);
2420
2421         auto transaction = m_pageLoadState.transaction();
2422         m_pageLoadState.setCanGoBack(transaction, m_backForwardList->backItem());
2423         m_pageLoadState.setCanGoForward(transaction, m_backForwardList->forwardItem());
2424
2425         // The back / forward list was restored from a sessionState so we don't want to snapshot the current
2426         // page when navigating away. Suppress navigation snapshotting until the next load has committed
2427         m_suppressAutomaticNavigationSnapshotting = true;
2428     }
2429
2430     // FIXME: Navigating should be separate from state restoration.
2431     if (navigate) {
2432         m_sessionRestorationRenderTreeSize = sessionState.renderTreeSize;
2433         if (!m_sessionRestorationRenderTreeSize)
2434             m_hitRenderTreeSizeThreshold = true; // If we didn't get data on renderTreeSize, just don't fire the milestone.
2435
2436         if (!sessionState.provisionalURL.isNull())
2437             return loadRequest(sessionState.provisionalURL);
2438
2439         if (hasBackForwardList) {
2440             // FIXME: Do we have to null check the back forward list item here?
2441             if (WebBackForwardListItem* item = m_backForwardList->currentItem())
2442                 return goToBackForwardItem(item);
2443         }
2444     }
2445
2446     return nullptr;
2447 }
2448
2449 bool WebPageProxy::supportsTextZoom() const
2450 {
2451     // FIXME (118840): This should also return false for standalone media and plug-in documents.
2452     if (!m_mainFrame || m_mainFrame->isDisplayingStandaloneImageDocument())
2453         return false;
2454
2455     return true;
2456 }
2457  
2458 void WebPageProxy::setTextZoomFactor(double zoomFactor)
2459 {
2460     if (!isValid())
2461         return;
2462
2463     if (m_textZoomFactor == zoomFactor)
2464         return;
2465
2466     m_textZoomFactor = zoomFactor;
2467     m_process->send(Messages::WebPage::SetTextZoomFactor(m_textZoomFactor), m_pageID); 
2468 }
2469
2470 void WebPageProxy::setPageZoomFactor(double zoomFactor)
2471 {
2472     if (!isValid())
2473         return;
2474
2475     if (m_pageZoomFactor == zoomFactor)
2476         return;
2477
2478     hideValidationMessage();
2479
2480     m_pageZoomFactor = zoomFactor;
2481     m_process->send(Messages::WebPage::SetPageZoomFactor(m_pageZoomFactor), m_pageID); 
2482 }
2483
2484 void WebPageProxy::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
2485 {
2486     if (!isValid())
2487         return;
2488
2489     if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor)
2490         return;
2491
2492     hideValidationMessage();
2493
2494     m_pageZoomFactor = pageZoomFactor;
2495     m_textZoomFactor = textZoomFactor;
2496     m_process->send(Messages::WebPage::SetPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor), m_pageID); 
2497 }
2498
2499 double WebPageProxy::pageZoomFactor() const
2500 {
2501     // Zoom factor for non-PDF pages persists across page loads. We maintain a separate member variable for PDF
2502     // zoom which ensures that we don't use the PDF zoom for a normal page.
2503     if (m_mainFramePluginHandlesPageScaleGesture)
2504         return m_pluginZoomFactor;
2505     return m_pageZoomFactor;
2506 }
2507
2508 double WebPageProxy::pageScaleFactor() const
2509 {
2510     // PDF documents use zoom and scale factors to size themselves appropriately in the window. We store them
2511     // separately but decide which to return based on the main frame.
2512     if (m_mainFramePluginHandlesPageScaleGesture)
2513         return m_pluginScaleFactor;
2514     return m_pageScaleFactor;
2515 }
2516
2517 void WebPageProxy::scalePage(double scale, const IntPoint& origin)
2518 {
2519     ASSERT(scale > 0);
2520
2521     if (!isValid())
2522         return;
2523
2524     m_pageScaleFactor = scale;
2525     m_process->send(Messages::WebPage::ScalePage(scale, origin), m_pageID);
2526 }
2527
2528 void WebPageProxy::scalePageInViewCoordinates(double scale, const IntPoint& centerInViewCoordinates)
2529 {
2530     ASSERT(scale > 0);
2531
2532     if (!isValid())
2533         return;
2534
2535     m_pageScaleFactor = scale;
2536     m_process->send(Messages::WebPage::ScalePageInViewCoordinates(scale, centerInViewCoordinates), m_pageID);
2537 }
2538
2539 void WebPageProxy::scaleView(double scale)
2540 {
2541     ASSERT(scale > 0);
2542
2543     if (!isValid())
2544         return;
2545
2546     m_viewScaleFactor = scale;
2547     m_process->send(Messages::WebPage::ScaleView(scale), m_pageID);
2548 }
2549
2550 void WebPageProxy::setIntrinsicDeviceScaleFactor(float scaleFactor)
2551 {
2552     if (m_intrinsicDeviceScaleFactor == scaleFactor)
2553         return;
2554
2555     m_intrinsicDeviceScaleFactor = scaleFactor;
2556
2557     if (m_drawingArea)
2558         m_drawingArea->deviceScaleFactorDidChange();
2559 }
2560
2561 void WebPageProxy::windowScreenDidChange(PlatformDisplayID displayID)
2562 {
2563     if (!isValid())
2564         return;
2565
2566     m_process->send(Messages::WebPage::WindowScreenDidChange(displayID), m_pageID);
2567 }
2568
2569 float WebPageProxy::deviceScaleFactor() const
2570 {
2571     if (m_customDeviceScaleFactor)
2572         return m_customDeviceScaleFactor;
2573     return m_intrinsicDeviceScaleFactor;
2574 }
2575
2576 void WebPageProxy::setCustomDeviceScaleFactor(float customScaleFactor)
2577 {
2578     if (!isValid())
2579         return;
2580
2581     // FIXME: Remove this once we bump cairo requirements to support HiDPI.
2582     // https://bugs.webkit.org/show_bug.cgi?id=133378
2583 #if USE(CAIRO) && !HAVE(CAIRO_SURFACE_SET_DEVICE_SCALE)
2584     return;
2585 #endif
2586
2587     if (m_customDeviceScaleFactor == customScaleFactor)
2588         return;
2589
2590     float oldScaleFactor = deviceScaleFactor();
2591
2592     m_customDeviceScaleFactor = customScaleFactor;
2593
2594     if (deviceScaleFactor() != oldScaleFactor)
2595         m_drawingArea->deviceScaleFactorDidChange();
2596 }
2597
2598 void WebPageProxy::accessibilitySettingsDidChange()
2599 {
2600     if (!isValid())
2601         return;
2602
2603     m_process->send(Messages::WebPage::AccessibilitySettingsDidChange(), m_pageID);
2604 }
2605
2606 void WebPageProxy::setUseFixedLayout(bool fixed)
2607 {
2608     if (!isValid())
2609         return;
2610
2611     // This check is fine as the value is initialized in the web
2612     // process as part of the creation parameters.
2613     if (fixed == m_useFixedLayout)
2614         return;
2615
2616     m_useFixedLayout = fixed;
2617     if (!fixed)
2618         m_fixedLayoutSize = IntSize();
2619     m_process->send(Messages::WebPage::SetUseFixedLayout(fixed), m_pageID);
2620 }
2621
2622 void WebPageProxy::setFixedLayoutSize(const IntSize& size)
2623 {
2624     if (!isValid())
2625         return;
2626
2627     if (size == m_fixedLayoutSize)
2628         return;
2629
2630     m_fixedLayoutSize = size;
2631     m_process->send(Messages::WebPage::SetFixedLayoutSize(size), m_pageID);
2632 }
2633
2634 void WebPageProxy::listenForLayoutMilestones(WebCore::LayoutMilestones milestones)
2635 {
2636     if (!isValid())
2637         return;
2638     
2639     if (milestones == m_observedLayoutMilestones)
2640         return;
2641
2642     m_observedLayoutMilestones = milestones;
2643     m_process->send(Messages::WebPage::ListenForLayoutMilestones(milestones), m_pageID);
2644 }
2645
2646 void WebPageProxy::setSuppressScrollbarAnimations(bool suppressAnimations)
2647 {
2648     if (!isValid())
2649         return;
2650
2651     if (suppressAnimations == m_suppressScrollbarAnimations)
2652         return;
2653
2654     m_suppressScrollbarAnimations = suppressAnimations;
2655     m_process->send(Messages::WebPage::SetSuppressScrollbarAnimations(suppressAnimations), m_pageID);
2656 }
2657
2658 bool WebPageProxy::rubberBandsAtLeft() const
2659 {
2660     return m_rubberBandsAtLeft;
2661 }
2662
2663 void WebPageProxy::setRubberBandsAtLeft(bool rubberBandsAtLeft)
2664 {
2665     m_rubberBandsAtLeft = rubberBandsAtLeft;
2666 }
2667
2668 bool WebPageProxy::rubberBandsAtRight() const
2669 {
2670     return m_rubberBandsAtRight;
2671 }
2672
2673 void WebPageProxy::setRubberBandsAtRight(bool rubberBandsAtRight)
2674 {
2675     m_rubberBandsAtRight = rubberBandsAtRight;
2676 }
2677
2678 bool WebPageProxy::rubberBandsAtTop() const
2679 {
2680     return m_rubberBandsAtTop;
2681 }
2682
2683 void WebPageProxy::setRubberBandsAtTop(bool rubberBandsAtTop)
2684 {
2685     m_rubberBandsAtTop = rubberBandsAtTop;
2686 }
2687
2688 bool WebPageProxy::rubberBandsAtBottom() const
2689 {
2690     return m_rubberBandsAtBottom;
2691 }
2692
2693 void WebPageProxy::setRubberBandsAtBottom(bool rubberBandsAtBottom)
2694 {
2695     m_rubberBandsAtBottom = rubberBandsAtBottom;
2696 }
2697     
2698 void WebPageProxy::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding)
2699 {
2700     if (enableVerticalRubberBanding == m_enableVerticalRubberBanding)
2701         return;
2702
2703     m_enableVerticalRubberBanding = enableVerticalRubberBanding;
2704
2705     if (!isValid())
2706         return;
2707     m_process->send(Messages::WebPage::SetEnableVerticalRubberBanding(enableVerticalRubberBanding), m_pageID);
2708 }
2709     
2710 bool WebPageProxy::verticalRubberBandingIsEnabled() const
2711 {
2712     return m_enableVerticalRubberBanding;
2713 }
2714     
2715 void WebPageProxy::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding)
2716 {
2717     if (enableHorizontalRubberBanding == m_enableHorizontalRubberBanding)
2718         return;
2719
2720     m_enableHorizontalRubberBanding = enableHorizontalRubberBanding;
2721
2722     if (!isValid())
2723         return;
2724     m_process->send(Messages::WebPage::SetEnableHorizontalRubberBanding(enableHorizontalRubberBanding), m_pageID);
2725 }
2726     
2727 bool WebPageProxy::horizontalRubberBandingIsEnabled() const
2728 {
2729     return m_enableHorizontalRubberBanding;
2730 }
2731
2732 void WebPageProxy::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage)
2733 {
2734     if (backgroundExtendsBeyondPage == m_backgroundExtendsBeyondPage)
2735         return;
2736
2737     m_backgroundExtendsBeyondPage = backgroundExtendsBeyondPage;
2738
2739     if (!isValid())
2740         return;
2741     m_process->send(Messages::WebPage::SetBackgroundExtendsBeyondPage(backgroundExtendsBeyondPage), m_pageID);
2742 }
2743
2744 bool WebPageProxy::backgroundExtendsBeyondPage() const
2745 {
2746     return m_backgroundExtendsBeyondPage;
2747 }
2748
2749 void WebPageProxy::setPaginationMode(WebCore::Pagination::Mode mode)
2750 {
2751     if (mode == m_paginationMode)
2752         return;
2753
2754     m_paginationMode = mode;
2755
2756     if (!isValid())
2757         return;
2758     m_process->send(Messages::WebPage::SetPaginationMode(mode), m_pageID);
2759 }
2760
2761 void WebPageProxy::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
2762 {
2763     if (behavesLikeColumns == m_paginationBehavesLikeColumns)
2764         return;
2765
2766     m_paginationBehavesLikeColumns = behavesLikeColumns;
2767
2768     if (!isValid())
2769         return;
2770     m_process->send(Messages::WebPage::SetPaginationBehavesLikeColumns(behavesLikeColumns), m_pageID);
2771 }
2772
2773 void WebPageProxy::setPageLength(double pageLength)
2774 {
2775     if (pageLength == m_pageLength)
2776         return;
2777
2778     m_pageLength = pageLength;
2779
2780     if (!isValid())
2781         return;
2782     m_process->send(Messages::WebPage::SetPageLength(pageLength), m_pageID);
2783 }
2784
2785 void WebPageProxy::setGapBetweenPages(double gap)
2786 {
2787     if (gap == m_gapBetweenPages)
2788         return;
2789
2790     m_gapBetweenPages = gap;
2791
2792     if (!isValid())
2793         return;
2794     m_process->send(Messages::WebPage::SetGapBetweenPages(gap), m_pageID);
2795 }
2796
2797 void WebPageProxy::setPaginationLineGridEnabled(bool lineGridEnabled)
2798 {
2799     if (lineGridEnabled == m_paginationLineGridEnabled)
2800         return;
2801     
2802     m_paginationLineGridEnabled = lineGridEnabled;
2803     
2804     if (!isValid())
2805         return;
2806     m_process->send(Messages::WebPage::SetPaginationLineGridEnabled(lineGridEnabled), m_pageID);
2807 }
2808
2809 void WebPageProxy::pageScaleFactorDidChange(double scaleFactor)
2810 {
2811     m_pageScaleFactor = scaleFactor;
2812 }
2813
2814 void WebPageProxy::pluginScaleFactorDidChange(double pluginScaleFactor)
2815 {
2816     m_pluginScaleFactor = pluginScaleFactor;
2817 }
2818
2819 void WebPageProxy::pluginZoomFactorDidChange(double pluginZoomFactor)
2820 {
2821     m_pluginZoomFactor = pluginZoomFactor;
2822 }
2823
2824 void WebPageProxy::findStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
2825 {
2826     if (string.isEmpty()) {
2827         didFindStringMatches(string, Vector<Vector<WebCore::IntRect>> (), 0);
2828         return;
2829     }
2830
2831     m_process->send(Messages::WebPage::FindStringMatches(string, options, maxMatchCount), m_pageID);
2832 }
2833
2834 void WebPageProxy::findString(const String& string, FindOptions options, unsigned maxMatchCount)
2835 {
2836     m_process->send(Messages::WebPage::FindString(string, options, maxMatchCount), m_pageID);
2837 }
2838
2839 void WebPageProxy::getImageForFindMatch(int32_t matchIndex)
2840 {
2841     m_process->send(Messages::WebPage::GetImageForFindMatch(matchIndex), m_pageID);
2842 }
2843
2844 void WebPageProxy::selectFindMatch(int32_t matchIndex)
2845 {
2846     m_process->send(Messages::WebPage::SelectFindMatch(matchIndex), m_pageID);
2847 }
2848
2849 void WebPageProxy::hideFindUI()
2850 {
2851     m_process->send(Messages::WebPage::HideFindUI(), m_pageID);
2852 }
2853
2854 void WebPageProxy::countStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
2855 {
2856     if (!isValid())
2857         return;
2858
2859     m_process->send(Messages::WebPage::CountStringMatches(string, options, maxMatchCount), m_pageID);
2860 }
2861
2862 void WebPageProxy::runJavaScriptInMainFrame(const String& script, std::function<void (API::SerializedScriptValue*, bool hadException, const ExceptionDetails&, CallbackBase::Error)> callbackFunction)
2863 {
2864     if (!isValid()) {
2865         callbackFunction(nullptr, false, { }, CallbackBase::Error::Unknown);
2866         return;
2867     }
2868
2869     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2870     m_process->send(Messages::WebPage::RunJavaScriptInMainFrame(script, callbackID), m_pageID);
2871 }
2872
2873 void WebPageProxy::getRenderTreeExternalRepresentation(std::function<void (const String&, CallbackBase::Error)> callbackFunction)
2874 {
2875     if (!isValid()) {
2876         callbackFunction(String(), CallbackBase::Error::Unknown);
2877         return;
2878     }
2879     
2880     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2881     m_process->send(Messages::WebPage::GetRenderTreeExternalRepresentation(callbackID), m_pageID);
2882 }
2883
2884 void WebPageProxy::getSourceForFrame(WebFrameProxy* frame, std::function<void (const String&, CallbackBase::Error)> callbackFunction)
2885 {
2886     if (!isValid()) {
2887         callbackFunction(String(), CallbackBase::Error::Unknown);
2888         return;
2889     }
2890     
2891     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2892     m_loadDependentStringCallbackIDs.add(callbackID);
2893     m_process->send(Messages::WebPage::GetSourceForFrame(frame->frameID(), callbackID), m_pageID);
2894 }
2895
2896 void WebPageProxy::getContentsAsString(std::function<void (const String&, CallbackBase::Error)> callbackFunction)
2897 {
2898     if (!isValid()) {
2899         callbackFunction(String(), CallbackBase::Error::Unknown);
2900         return;
2901     }
2902     
2903     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2904     m_loadDependentStringCallbackIDs.add(callbackID);
2905     m_process->send(Messages::WebPage::GetContentsAsString(callbackID), m_pageID);
2906 }
2907
2908 void WebPageProxy::getBytecodeProfile(std::function<void (const String&, CallbackBase::Error)> callbackFunction)
2909 {
2910     if (!isValid()) {
2911         callbackFunction(String(), CallbackBase::Error::Unknown);
2912         return;
2913     }
2914     
2915     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2916     m_loadDependentStringCallbackIDs.add(callbackID);
2917     m_process->send(Messages::WebPage::GetBytecodeProfile(callbackID), m_pageID);
2918 }
2919
2920 void WebPageProxy::getSamplingProfilerOutput(std::function<void (const String&, CallbackBase::Error)> callbackFunction)
2921 {
2922     if (!isValid()) {
2923         callbackFunction(String(), CallbackBase::Error::Unknown);
2924         return;
2925     }
2926     
2927     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2928     m_loadDependentStringCallbackIDs.add(callbackID);
2929     m_process->send(Messages::WebPage::GetSamplingProfilerOutput(callbackID), m_pageID);
2930 }
2931
2932 void WebPageProxy::isWebProcessResponsive(std::function<void (bool isWebProcessResponsive)> callbackFunction)
2933 {
2934     if (!isValid()) {
2935         RunLoop::main().dispatch([callbackFunction = WTFMove(callbackFunction)] {
2936             bool isWebProcessResponsive = true;
2937             callbackFunction(isWebProcessResponsive);
2938         });
2939         return;
2940     }
2941
2942     m_process->isResponsive(callbackFunction);
2943 }
2944
2945 #if ENABLE(MHTML)
2946 void WebPageProxy::getContentsAsMHTMLData(std::function<void (API::Data*, CallbackBase::Error)> callbackFunction)
2947 {
2948     if (!isValid()) {
2949         callbackFunction(nullptr, CallbackBase::Error::Unknown);
2950         return;
2951     }
2952
2953     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2954     m_process->send(Messages::WebPage::GetContentsAsMHTMLData(callbackID), m_pageID);
2955 }
2956 #endif
2957
2958 void WebPageProxy::getSelectionOrContentsAsString(std::function<void (const String&, CallbackBase::Error)> callbackFunction)
2959 {
2960     if (!isValid()) {
2961         callbackFunction(String(), CallbackBase::Error::Unknown);
2962         return;
2963     }
2964     
2965     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2966     m_process->send(Messages::WebPage::GetSelectionOrContentsAsString(callbackID), m_pageID);
2967 }
2968
2969 void WebPageProxy::getSelectionAsWebArchiveData(std::function<void (API::Data*, CallbackBase::Error)> callbackFunction)
2970 {
2971     if (!isValid()) {
2972         callbackFunction(nullptr, CallbackBase::Error::Unknown);
2973         return;
2974     }
2975     
2976     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2977     m_process->send(Messages::WebPage::GetSelectionAsWebArchiveData(callbackID), m_pageID);
2978 }
2979
2980 void WebPageProxy::getMainResourceDataOfFrame(WebFrameProxy* frame, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction)
2981 {
2982     if (!isValid() || !frame) {
2983         callbackFunction(nullptr, CallbackBase::Error::Unknown);
2984         return;
2985     }
2986     
2987     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2988     m_process->send(Messages::WebPage::GetMainResourceDataOfFrame(frame->frameID(), callbackID), m_pageID);
2989 }
2990
2991 void WebPageProxy::getResourceDataFromFrame(WebFrameProxy* frame, API::URL* resourceURL, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction)
2992 {
2993     if (!isValid()) {
2994         callbackFunction(nullptr, CallbackBase::Error::Unknown);
2995         return;
2996     }
2997     
2998     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
2999     m_process->send(Messages::WebPage::GetResourceDataFromFrame(frame->frameID(), resourceURL->string(), callbackID), m_pageID);
3000 }
3001
3002 void WebPageProxy::getWebArchiveOfFrame(WebFrameProxy* frame, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction)
3003 {
3004     if (!isValid()) {
3005         callbackFunction(nullptr, CallbackBase::Error::Unknown);
3006         return;
3007     }
3008     
3009     uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken());
3010     m_process->send(Messages::WebPage::GetWebArchiveOfFrame(frame->frameID(), callbackID), m_pageID);
3011 }
3012
3013 void WebPageProxy::forceRepaint(PassRefPtr<VoidCallback> prpCallback)
3014 {
3015     RefPtr<VoidCallback> callback = prpCallback;
3016     if (!isValid()) {
3017         // FIXME: If the page is invalid we should not call the callback. It'd be better to just return false from forceRepaint.
3018         callback->invalidate(CallbackBase::Error::OwnerWasInvalidated);
3019         return;
3020     }
3021
3022     std::function<void (CallbackBase::Error)> didForceRepaintCallback = [this, callback](CallbackBase::Error error) {
3023         if (error != CallbackBase::Error::None) {
3024             callback->invalidate(error);
3025             return;
3026         }
3027
3028         if (!isValid()) {
3029             callback->invalidate(CallbackBase::Error::OwnerWasInvalidated);
3030             return;
3031         }
3032     
3033         callAfterNextPresentationUpdate([callback](CallbackBase::Error error) {
3034             if (error != CallbackBase::Error::None) {
3035                 callback->invalidate(error);
3036                 return;
3037             }
3038
3039             callback->performCallback();
3040         });
3041     };
3042
3043     uint64_t callbackID = m_callbacks.put(didForceRepaintCallback, m_process->throttler().backgroundActivityToken());
3044     m_drawingArea->waitForBackingStoreUpdateOnNextPaint();
3045     m_process->send(Messages::WebPage::ForceRepaint(callbackID), m_pageID); 
3046 }
3047
3048 static OptionSet<IPC::SendOption> printingSendOptions(bool isPerformingDOMPrintOperation)
3049 {
3050     if (isPerformingDOMPrintOperation)
3051         return IPC::SendOption::DispatchMessageEvenWhenWaitingForSyncReply;
3052
3053     return { };
3054 }
3055
3056 void WebPageProxy::preferencesDidChange()
3057 {
3058     if (!isValid())
3059         return;
3060
3061 #if ENABLE(INSPECTOR_SERVER)
3062     if (m_preferences->developerExtrasEnabled())
3063         inspector()->enableRemoteInspection();
3064 #endif
3065
3066     updateThrottleState();
3067     updateHiddenPageThrottlingAutoIncreases();
3068
3069     m_pageClient.preferencesDidChange();
3070
3071     // FIXME: It probably makes more sense to send individual preference changes.
3072     // However, WebKitTestRunner depends on getting a preference change notification
3073     // even if nothing changed in UI process, so that overrides get removed.
3074
3075     // Preferences need to be updated during synchronous printing to make "print backgrounds" preference work when toggled from a print dialog checkbox.
3076     m_process->send(Messages::WebPage::PreferencesDidChange(preferencesStore()), m_pageID, printingSendOptions(m_isPerformingDOMPrintOperation));
3077 }
3078
3079 void WebPageProxy::didCreateMainFrame(uint64_t frameID)
3080 {
3081     PageClientProtector protector(m_pageClient);
3082
3083     MESSAGE_CHECK(!m_mainFrame);
3084     MESSAGE_CHECK(m_process->canCreateFrame(frameID));
3085
3086     m_mainFrame = WebFrameProxy::create(this, frameID);
3087
3088     // Add the frame to the process wide map.
3089     m_process->frameCreated(frameID, m_mainFrame.get());
3090 }
3091
3092 void WebPageProxy::didCreateSubframe(uint64_t frameID)
3093 {
3094     PageClientProtector protector(m_pageClient);
3095
3096     MESSAGE_CHECK(m_mainFrame);
3097     MESSAGE_CHECK(m_process->canCreateFrame(frameID));
3098     
3099     RefPtr<WebFrameProxy> subFrame = WebFrameProxy::create(this, frameID);
3100
3101     // Add the frame to the process wide map.
3102     m_process->frameCreated(frameID, subFrame.get());
3103 }
3104
3105 double WebPageProxy::estimatedProgress() const
3106 {
3107     return m_pageLoadState.estimatedProgress();
3108 }
3109
3110 void WebPageProxy::didStartProgress()
3111 {
3112     PageClientProtector protector(m_pageClient);
3113
3114     auto transaction = m_pageLoadState.transaction();
3115     m_pageLoadState.didStartProgress(transaction);
3116
3117     m_pageLoadState.commitChanges();
3118     m_loaderClient->didStartProgress(*this);
3119 }
3120
3121 void WebPageProxy::didChangeProgress(double value)
3122 {
3123     PageClientProtector protector(m_pageClient);
3124
3125     auto transaction = m_pageLoadState.transaction();
3126     m_pageLoadState.didChangeProgress(transaction, value);
3127
3128     m_pageLoadState.commitChanges();
3129     m_loaderClient->didChangeProgress(*this);
3130 }
3131
3132 void WebPageProxy::didFinishProgress()
3133 {
3134     PageClientProtector protector(m_pageClient);
3135
3136     auto transaction = m_pageLoadState.transaction();
3137     m_pageLoadState.didFinishProgress(transaction);
3138
3139     m_pageLoadState.commitChanges();
3140     m_loaderClient->didFinishProgress(*this);
3141 }
3142
3143 void WebPageProxy::setNetworkRequestsInProgress(bool networkRequestsInProgress)
3144 {
3145     auto transaction = m_pageLoadState.transaction();
3146     m_pageLoadState.setNetworkRequestsInProgress(transaction, networkRequestsInProgress);
3147 }
3148
3149 void WebPageProxy::hasInsecureContent(HasInsecureContent& hasInsecureContent)
3150 {
3151     hasInsecureContent = m_pageLoadState.committedHasInsecureContent() ? HasInsecureContent::Yes : HasInsecureContent::No;
3152 }
3153
3154 void WebPageProxy::didDestroyNavigation(uint64_t navigationID)
3155 {
3156     PageClientProtector protector(m_pageClient);
3157
3158     // FIXME: Message check the navigationID.
3159     m_navigationState->didDestroyNavigation(navigationID);
3160 }
3161
3162 void WebPageProxy::didStartProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& url, const String& unreachableURL, const UserData& userData)
3163 {
3164     PageClientProtector protector(m_pageClient);
3165
3166     auto transaction = m_pageLoadState.transaction();
3167
3168     m_pageLoadState.clearPendingAPIRequestURL(transaction);
3169
3170     WebFrameProxy* frame = m_process->webFrame(frameID);
3171     MESSAGE_CHECK(frame);
3172     MESSAGE_CHECK_URL(url);
3173
3174     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3175     RefPtr<API::Navigation> navigation;
3176     if (frame->isMainFrame() && navigationID)
3177         navigation = &navigationState().navigation(navigationID);
3178
3179     if (frame->isMainFrame())
3180         m_pageLoadState.didStartProvisionalLoad(transaction, url, unreachableURL);
3181
3182     frame->setUnreachableURL(unreachableURL);
3183     frame->didStartProvisionalLoad(url);
3184
3185     m_pageLoadState.commitChanges();
3186     if (m_navigationClient) {
3187         if (frame->isMainFrame())
3188             m_navigationClient->didStartProvisionalNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3189     } else
3190         m_loaderClient->didStartProvisionalLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3191 }
3192
3193 void WebPageProxy::didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& url, const UserData& userData)
3194 {
3195     PageClientProtector protector(m_pageClient);
3196
3197     WebFrameProxy* frame = m_process->webFrame(frameID);
3198     MESSAGE_CHECK(frame);
3199     MESSAGE_CHECK_URL(url);
3200
3201     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3202     RefPtr<API::Navigation> navigation;
3203     if (frame->isMainFrame() && navigationID)
3204         navigation = &navigationState().navigation(navigationID);
3205
3206     auto transaction = m_pageLoadState.transaction();
3207
3208     if (frame->isMainFrame())
3209         m_pageLoadState.didReceiveServerRedirectForProvisionalLoad(transaction, url);
3210
3211     frame->didReceiveServerRedirectForProvisionalLoad(url);
3212
3213     m_pageLoadState.commitChanges();
3214     if (m_navigationClient) {
3215         if (frame->isMainFrame())
3216             m_navigationClient->didReceiveServerRedirectForProvisionalNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3217     } else
3218         m_loaderClient->didReceiveServerRedirectForProvisionalLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3219 }
3220
3221 void WebPageProxy::didChangeProvisionalURLForFrame(uint64_t frameID, uint64_t, const String& url)
3222 {
3223     PageClientProtector protector(m_pageClient);
3224
3225     WebFrameProxy* frame = m_process->webFrame(frameID);
3226     MESSAGE_CHECK(frame);
3227     MESSAGE_CHECK(frame->frameLoadState().state() == FrameLoadState::State::Provisional);
3228     MESSAGE_CHECK_URL(url);
3229
3230     auto transaction = m_pageLoadState.transaction();
3231
3232     // Internally, we handle this the same way we handle a server redirect. There are no client callbacks
3233     // for this, but if this is the main frame, clients may observe a change to the page's URL.
3234     if (frame->isMainFrame())
3235         m_pageLoadState.didReceiveServerRedirectForProvisionalLoad(transaction, url);
3236
3237     frame->didReceiveServerRedirectForProvisionalLoad(url);
3238 }
3239
3240 void WebPageProxy::didFailProvisionalLoadForFrame(uint64_t frameID, const SecurityOriginData& frameSecurityOrigin, uint64_t navigationID, const String& provisionalURL, const ResourceError& error, const UserData& userData)
3241 {
3242     PageClientProtector protector(m_pageClient);
3243
3244     WebFrameProxy* frame = m_process->webFrame(frameID);
3245     MESSAGE_CHECK(frame);
3246
3247     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3248     RefPtr<API::Navigation> navigation;
3249     if (frame->isMainFrame() && navigationID)
3250         navigation = navigationState().takeNavigation(navigationID);
3251
3252     auto transaction = m_pageLoadState.transaction();
3253
3254     if (frame->isMainFrame())
3255         m_pageLoadState.didFailProvisionalLoad(transaction);
3256
3257     frame->didFailProvisionalLoad();
3258
3259     m_pageLoadState.commitChanges();
3260
3261     ASSERT(!m_failingProvisionalLoadURL);
3262     m_failingProvisionalLoadURL = provisionalURL;
3263
3264     if (m_navigationClient) {
3265         if (frame->isMainFrame())
3266             m_navigationClient->didFailProvisionalNavigationWithError(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get());
3267         else {
3268             // FIXME: Get the main frame's current navigation.
3269             m_navigationClient->didFailProvisionalLoadInSubframeWithError(*this, *frame, frameSecurityOrigin, nullptr, error, m_process->transformHandlesToObjects(userData.object()).get());
3270         }
3271     } else
3272         m_loaderClient->didFailProvisionalLoadWithErrorForFrame(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get());
3273
3274     m_failingProvisionalLoadURL = { };
3275 }
3276
3277 void WebPageProxy::clearLoadDependentCallbacks()
3278 {
3279     Vector<uint64_t> callbackIDsCopy;
3280     copyToVector(m_loadDependentStringCallbackIDs, callbackIDsCopy);
3281     m_loadDependentStringCallbackIDs.clear();
3282
3283     for (size_t i = 0; i < callbackIDsCopy.size(); ++i) {
3284         auto callback = m_callbacks.take<StringCallback>(callbackIDsCopy[i]);
3285         if (callback)
3286             callback->invalidate();
3287     }
3288 }
3289
3290 void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& mimeType, bool frameHasCustomContentProvider, uint32_t opaqueFrameLoadType, const WebCore::CertificateInfo& certificateInfo, bool containsPluginDocument, std::optional<HasInsecureContent> hasInsecureContent, const UserData& userData)
3291 {
3292     PageClientProtector protector(m_pageClient);
3293
3294     WebFrameProxy* frame = m_process->webFrame(frameID);
3295     MESSAGE_CHECK(frame);
3296
3297     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3298     RefPtr<API::Navigation> navigation;
3299     if (frame->isMainFrame() && navigationID)
3300         navigation = &navigationState().navigation(navigationID);
3301
3302 #if PLATFORM(IOS)
3303     if (frame->isMainFrame()) {
3304         m_hasReceivedLayerTreeTransactionAfterDidCommitLoad = false;
3305         m_firstLayerTreeTransactionIdAfterDidCommitLoad = downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea()).nextLayerTreeTransactionID();
3306     }
3307 #endif
3308
3309     auto transaction = m_pageLoadState.transaction();
3310     Ref<WebCertificateInfo> webCertificateInfo = WebCertificateInfo::create(certificateInfo);
3311     bool markPageInsecure = hasInsecureContent ? hasInsecureContent.value() == HasInsecureContent::Yes : m_treatsSHA1CertificatesAsInsecure && certificateInfo.containsNonRootSHA1SignedCertificate();
3312
3313     if (frame->isMainFrame()) {
3314         m_pageLoadState.didCommitLoad(transaction, webCertificateInfo, markPageInsecure);
3315         m_suppressAutomaticNavigationSnapshotting = false;
3316     } else if (markPageInsecure)
3317         m_pageLoadState.didDisplayOrRunInsecureContent(transaction);
3318
3319 #if USE(APPKIT)
3320     // FIXME (bug 59111): didCommitLoadForFrame comes too late when restoring a page from b/f cache, making us disable secure event mode in password fields.
3321     // FIXME: A load going on in one frame shouldn't affect text editing in other frames on the page.
3322     m_pageClient.resetSecureInputState();
3323     m_pageClient.dismissContentRelativeChildWindows();
3324 #endif
3325
3326     clearLoadDependentCallbacks();
3327
3328     frame->didCommitLoad(mimeType, webCertificateInfo, containsPluginDocument);
3329
3330     if (frame->isMainFrame()) {
3331         m_mainFrameHasCustomContentProvider = frameHasCustomContentProvider;
3332
3333         if (m_mainFrameHasCustomContentProvider) {
3334             // Always assume that the main frame is pinned here, since the custom representation view will handle
3335             // any wheel events and dispatch them to the WKView when necessary.
3336             m_mainFrameIsPinnedToLeftSide = true;
3337             m_mainFrameIsPinnedToRightSide = true;
3338             m_mainFrameIsPinnedToTopSide = true;
3339             m_mainFrameIsPinnedToBottomSide = true;
3340
3341             m_uiClient->pinnedStateDidChange(*this);
3342         }
3343         m_pageClient.didCommitLoadForMainFrame(mimeType, frameHasCustomContentProvider);
3344     }
3345
3346     // Even if WebPage has the default pageScaleFactor (and therefore doesn't reset it),
3347     // WebPageProxy's cache of the value can get out of sync (e.g. in the case where a
3348     // plugin is handling page scaling itself) so we should reset it to the default
3349     // for standard main frame loads.
3350     if (frame->isMainFrame()) {
3351         if (static_cast<FrameLoadType>(opaqueFrameLoadType) == FrameLoadType::Standard) {
3352             m_pageScaleFactor = 1;
3353             m_pluginScaleFactor = 1;
3354             m_mainFramePluginHandlesPageScaleGesture = false;
3355         }
3356     }
3357
3358     m_pageLoadState.commitChanges();
3359     if (m_navigationClient) {
3360         if (frame->isMainFrame())
3361             m_navigationClient->didCommitNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3362     } else
3363         m_loaderClient->didCommitLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3364 }
3365
3366 void WebPageProxy::didFinishDocumentLoadForFrame(uint64_t frameID, uint64_t navigationID, const UserData& userData)
3367 {
3368     PageClientProtector protector(m_pageClient);
3369
3370     WebFrameProxy* frame = m_process->webFrame(frameID);
3371     MESSAGE_CHECK(frame);
3372
3373     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3374     RefPtr<API::Navigation> navigation;
3375     if (frame->isMainFrame() && navigationID)
3376         navigation = &navigationState().navigation(navigationID);
3377
3378     if (m_navigationClient) {
3379         if (frame->isMainFrame())
3380             m_navigationClient->didFinishDocumentLoad(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3381     } else
3382         m_loaderClient->didFinishDocumentLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3383 }
3384
3385 void WebPageProxy::didFinishLoadForFrame(uint64_t frameID, uint64_t navigationID, const UserData& userData)
3386 {
3387     PageClientProtector protector(m_pageClient);
3388
3389     WebFrameProxy* frame = m_process->webFrame(frameID);
3390     MESSAGE_CHECK(frame);
3391
3392     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3393     RefPtr<API::Navigation> navigation;
3394     if (frame->isMainFrame() && navigationID)
3395         navigation = &navigationState().navigation(navigationID);
3396
3397     auto transaction = m_pageLoadState.transaction();
3398
3399     bool isMainFrame = frame->isMainFrame();
3400     if (isMainFrame)
3401         m_pageLoadState.didFinishLoad(transaction);
3402
3403     if (isMainFrame && m_controlledByAutomation) {
3404         if (auto* automationSession = process().processPool().automationSession())
3405             automationSession->navigationOccurredForPage(*this);
3406     }
3407
3408     frame->didFinishLoad();
3409
3410     m_pageLoadState.commitChanges();
3411     if (m_navigationClient) {
3412         if (isMainFrame)
3413             m_navigationClient->didFinishNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3414     } else
3415         m_loaderClient->didFinishLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get());
3416
3417     if (isMainFrame)
3418         m_pageClient.didFinishLoadForMainFrame();
3419
3420     m_isLoadingAlternateHTMLStringForFailingProvisionalLoad = false;
3421 }
3422
3423 void WebPageProxy::didFailLoadForFrame(uint64_t frameID, uint64_t navigationID, const ResourceError& error, const UserData& userData)
3424 {
3425     PageClientProtector protector(m_pageClient);
3426
3427     WebFrameProxy* frame = m_process->webFrame(frameID);
3428     MESSAGE_CHECK(frame);
3429
3430     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3431     RefPtr<API::Navigation> navigation;
3432     if (frame->isMainFrame() && navigationID)
3433         navigation = &navigationState().navigation(navigationID);
3434
3435     clearLoadDependentCallbacks();
3436
3437     auto transaction = m_pageLoadState.transaction();
3438
3439     bool isMainFrame = frame->isMainFrame();
3440
3441     if (isMainFrame)
3442         m_pageLoadState.didFailLoad(transaction);
3443
3444     if (isMainFrame && m_controlledByAutomation) {
3445         if (auto* automationSession = process().processPool().automationSession())
3446             automationSession->navigationOccurredForPage(*this);
3447     }
3448
3449     frame->didFailLoad();
3450
3451     m_pageLoadState.commitChanges();
3452     if (m_navigationClient) {
3453         if (frame->isMainFrame())
3454             m_navigationClient->didFailNavigationWithError(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get());
3455     } else
3456         m_loaderClient->didFailLoadWithErrorForFrame(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get());
3457
3458     if (isMainFrame)
3459         m_pageClient.didFailLoadForMainFrame();
3460 }
3461
3462 void WebPageProxy::didSameDocumentNavigationForFrame(uint64_t frameID, uint64_t navigationID, uint32_t opaqueSameDocumentNavigationType, const String& url, const UserData& userData)
3463 {
3464     PageClientProtector protector(m_pageClient);
3465
3466     WebFrameProxy* frame = m_process->webFrame(frameID);
3467     MESSAGE_CHECK(frame);
3468     MESSAGE_CHECK_URL(url);
3469
3470     // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
3471     RefPtr<API::Navigation> navigation;
3472     if (frame->isMainFrame() && navigationID)
3473         navigation = &navigationState().navigation(navigationID);
3474
3475     auto transaction = m_pageLoadState.transaction();
3476
3477     bool isMainFrame = frame->isMainFrame();
3478     if (isMainFrame)
3479         m_pageLoadState.didSameDocumentNavigation(transaction, url);
3480
3481     if (isMainFrame && m_controlledByAutomation) {
3482         if (auto* automationSession = process().processPool().automationSession())
3483             automationSession->navigationOccurredForPage(*this);
3484     }
3485
3486     m_pageLoadState.clearPendingAPIRequestURL(transaction);
3487     frame->didSameDocumentNavigation(url);
3488
3489     m_pageLoadState.commitChanges();
3490
3491     SameDocumentNavigationType navigationType = static_cast<SameDocumentNavigationType>(opaqueSameDocumentNavigationType);
3492     if (m_navigationClient) {
3493         if (isMainFrame)
3494             m_navigationClient->didSameDocumentNavigation(*this, navigation.get(), navigationType, m_process->transformHandlesToObjects(userData.object()).get());
3495     } else
3496         m_loaderClient->didSameDocumentNavigationForFrame(*this, *frame, navigation.get(), navigationType, m_process->transformHandlesToObjects(userData.object()).get());
3497
3498     if (isMainFrame)
3499         m_pageClient.didSameDocumentNavigationForMainFrame(navigationType);
3500 }
3501
3502 void WebPageProxy::didReceiveTitleForFrame(uint64_t frameID, const String& title, const UserData& userData)
3503 {
3504     PageClientProtector protector(m_pageClient);
3505
3506     WebFrameProxy* frame = m_process->webFrame(frameID);
3507     MESSAGE_CHECK(frame);
3508
3509     auto transaction = m_pageLoadState.transaction();
3510
3511     if (frame->isMainFrame())
3512         m_pageLoadState.setTitle(transaction, title);
3513
3514     frame->didChangeTitle(title);
3515     
3516     m_pageLoadState.commitChanges();
3517     m_loaderClient->didReceiveTitleForFrame(*this, title, *frame, m_process->transformHandlesToObjects(userData.object()).get());
3518 }
3519
3520 void WebPageProxy::didFirstLayoutForFrame(uint64_t frameID, const UserData& userData)
3521 {
3522     PageClientProtector protector(m_pageClient);
3523
3524     WebFrameProxy* frame = m_process->webFrame(frameID);
3525     MESSAGE_CHECK(frame);
3526
3527     m_loaderClient->didFirstLayoutForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get());
3528 }
3529
3530 void WebPageProxy::didFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, const UserData& userData)
3531 {
3532     PageClientProtector protector(m_pageClient);
3533
3534     WebFrameProxy* frame = m_process->webFrame(frameID);
3535     MESSAGE_CHECK(frame);
3536
3537     m_loaderClient->didFirstVisuallyNonEmptyLayoutForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get());
3538
3539     if (frame->isMainFrame())
3540         m_pageClient.didFirstVisuallyNonEmptyLayoutForMainFrame();
3541 }
3542
3543 void WebPageProxy::didLayoutForCustomContentProvider()
3544 {
3545     didReachLayoutMilestone(DidFirstLayout | DidFirstVisuallyNonEmptyLayout | DidHitRelevantRepaintedObjectsAreaThreshold);
3546 }
3547
3548 void WebPageProxy::didReachLayoutMilestone(uint32_t layoutMilestones)
3549 {
3550     PageClientProtector protector(m_pageClient);
3551
3552     if (m_navigationClient)
3553         m_navigationClient->renderingProgressDidChange(*this, static_cast<LayoutMilestones>(layoutMilestones));
3554     else
3555         m_loaderClient->didReachLayoutMilestone(*this, static_cast<LayoutMilestones>(layoutMilestones));
3556 }
3557
3558 void WebPageProxy::didDisplayInsecureContentForFrame(uint64_t frameID, const UserData& userData)
3559 {
3560     PageClientProtector protector(m_pageClient);
3561
3562     WebFrameProxy* frame = m_process->webFrame(frameID);
3563     MESSAGE_CHECK(frame);
3564
3565     auto transaction = m_pageLoadState.transaction();
3566     m_pageLoadState.didDisplayOrRunInsecureContent(transaction);
3567
3568     m_pageLoadState.commitChanges();
3569     m_loaderClient->didDisplayInsecureContentForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get());
3570 }
3571
3572 void WebPageProxy::didRunInsecureContentForFrame(uint64_t frameID, const UserData& userData)
3573 {
3574     PageClientProtector protector(m_pageClient);
3575
3576     WebFrameProxy* frame = m_process->webFrame(frameID);
3577     MESSAGE_CHECK(frame);
3578
3579     auto transaction = m_pageLoadState.transaction();
3580     m_pageLoadState.didDisplayOrRunInsecureContent(transaction);
3581
3582     m_pageLoadState.commitChanges();
3583     m_loaderClient->didRunInsecureContentForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get());
3584 }
3585
3586 void WebPageProxy::didDetectXSSForFrame(uint64_t frameID, const UserData& userData)
3587 {
3588     PageClientProtector protector(m_pageClient);