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