Move URL from WebCore to WTF
[WebKit-https.git] / Source / WebKit / UIProcess / Cocoa / NavigationState.mm
1 /*
2  * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "NavigationState.h"
28
29 #if WK_API_ENABLED
30
31 #import "APIFrameInfo.h"
32 #import "APINavigationData.h"
33 #import "APINavigationResponse.h"
34 #import "APIString.h"
35 #import "APIURL.h"
36 #import "APIWebsiteDataStore.h"
37 #import "AuthenticationChallengeDisposition.h"
38 #import "AuthenticationDecisionListener.h"
39 #import "CompletionHandlerCallChecker.h"
40 #import "Logging.h"
41 #import "NavigationActionData.h"
42 #import "PageLoadState.h"
43 #import "WKBackForwardListInternal.h"
44 #import "WKBackForwardListItemInternal.h"
45 #import "WKFrameInfoInternal.h"
46 #import "WKHistoryDelegatePrivate.h"
47 #import "WKNSDictionary.h"
48 #import "WKNSURLAuthenticationChallenge.h"
49 #import "WKNSURLExtras.h"
50 #import "WKNSURLRequest.h"
51 #import "WKNavigationActionInternal.h"
52 #import "WKNavigationDataInternal.h"
53 #import "WKNavigationDelegatePrivate.h"
54 #import "WKNavigationInternal.h"
55 #import "WKNavigationResponseInternal.h"
56 #import "WKReloadFrameErrorRecoveryAttempter.h"
57 #import "WKWebViewInternal.h"
58 #import "WebCredential.h"
59 #import "WebFrameProxy.h"
60 #import "WebNavigationState.h"
61 #import "WebPageProxy.h"
62 #import "WebProcessProxy.h"
63 #import "WebProtectionSpace.h"
64 #import "_WKErrorRecoveryAttempting.h"
65 #import "_WKFrameHandleInternal.h"
66 #import "_WKRenderingProgressEventsInternal.h"
67 #import "_WKSameDocumentNavigationTypeInternal.h"
68 #import "_WKWebsitePoliciesInternal.h"
69 #import <WebCore/Credential.h>
70 #import <WebCore/SSLKeyGenerator.h>
71 #import <WebCore/SecurityOriginData.h>
72 #import <WebCore/SerializedCryptoKeyWrap.h>
73 #import <wtf/BlockPtr.h>
74 #import <wtf/NeverDestroyed.h>
75 #import <wtf/URL.h>
76
77 #if HAVE(APP_LINKS)
78 #import <pal/spi/cocoa/LaunchServicesSPI.h>
79 #endif
80
81 #if USE(QUICK_LOOK)
82 #import "QuickLookDocumentData.h"
83 #endif
84
85 namespace WebKit {
86 using namespace WebCore;
87
88 static HashMap<WebPageProxy*, NavigationState*>& navigationStates()
89 {
90     static NeverDestroyed<HashMap<WebPageProxy*, NavigationState*>> navigationStates;
91
92     return navigationStates;
93 }
94
95 NavigationState::NavigationState(WKWebView *webView)
96     : m_webView(webView)
97     , m_navigationDelegateMethods()
98     , m_historyDelegateMethods()
99 #if PLATFORM(IOS_FAMILY)
100     , m_releaseActivityTimer(RunLoop::current(), this, &NavigationState::releaseNetworkActivityTokenAfterLoadCompletion)
101 #endif
102 {
103     ASSERT(m_webView->_page);
104     ASSERT(!navigationStates().contains(m_webView->_page.get()));
105
106     navigationStates().add(m_webView->_page.get(), this);
107     m_webView->_page->pageLoadState().addObserver(*this);
108 }
109
110 NavigationState::~NavigationState()
111 {
112     ASSERT(navigationStates().get(m_webView->_page.get()) == this);
113
114     navigationStates().remove(m_webView->_page.get());
115     m_webView->_page->pageLoadState().removeObserver(*this);
116 }
117
118 NavigationState& NavigationState::fromWebPage(WebPageProxy& webPageProxy)
119 {
120     ASSERT(navigationStates().contains(&webPageProxy));
121
122     return *navigationStates().get(&webPageProxy);
123 }
124
125 UniqueRef<API::NavigationClient> NavigationState::createNavigationClient()
126 {
127     return makeUniqueRef<NavigationClient>(*this);
128 }
129     
130 UniqueRef<API::HistoryClient> NavigationState::createHistoryClient()
131 {
132     return makeUniqueRef<HistoryClient>(*this);
133 }
134
135 RetainPtr<id <WKNavigationDelegate> > NavigationState::navigationDelegate()
136 {
137     return m_navigationDelegate.get();
138 }
139
140 void NavigationState::setNavigationDelegate(id <WKNavigationDelegate> delegate)
141 {
142     m_navigationDelegate = delegate;
143
144     m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionDecisionHandler = [delegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)];
145     m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionDecisionHandlerWebsitePolicies = [delegate respondsToSelector:@selector(_webView:decidePolicyForNavigationAction:decisionHandler:)];
146     m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionUserInfoDecisionHandlerWebsitePolicies = [delegate respondsToSelector:@selector(_webView:decidePolicyForNavigationAction:userInfo:decisionHandler:)];
147     m_navigationDelegateMethods.webViewDecidePolicyForNavigationResponseDecisionHandler = [delegate respondsToSelector:@selector(webView:decidePolicyForNavigationResponse:decisionHandler:)];
148
149     m_navigationDelegateMethods.webViewDidStartProvisionalNavigation = [delegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)];
150     m_navigationDelegateMethods.webViewDidStartProvisionalNavigationUserInfo = [delegate respondsToSelector:@selector(_webView:didStartProvisionalNavigation:userInfo:)];
151     m_navigationDelegateMethods.webViewDidReceiveServerRedirectForProvisionalNavigation = [delegate respondsToSelector:@selector(webView:didReceiveServerRedirectForProvisionalNavigation:)];
152     m_navigationDelegateMethods.webViewDidFailProvisionalNavigationWithError = [delegate respondsToSelector:@selector(webView:didFailProvisionalNavigation:withError:)];
153     m_navigationDelegateMethods.webViewDidCommitNavigation = [delegate respondsToSelector:@selector(webView:didCommitNavigation:)];
154     m_navigationDelegateMethods.webViewDidFinishNavigation = [delegate respondsToSelector:@selector(webView:didFinishNavigation:)];
155     m_navigationDelegateMethods.webViewDidFailNavigationWithError = [delegate respondsToSelector:@selector(webView:didFailNavigation:withError:)];
156     m_navigationDelegateMethods.webViewDidFailNavigationWithErrorUserInfo = [delegate respondsToSelector:@selector(_webView:didFailNavigation:withError:userInfo:)];
157
158     m_navigationDelegateMethods.webViewNavigationDidFailProvisionalLoadInSubframeWithError = [delegate respondsToSelector:@selector(_webView:navigation:didFailProvisionalLoadInSubframe:withError:)];
159     m_navigationDelegateMethods.webViewWillPerformClientRedirect = [delegate respondsToSelector:@selector(_webView:willPerformClientRedirectToURL:delay:)];
160     m_navigationDelegateMethods.webViewDidPerformClientRedirect = [delegate respondsToSelector:@selector(_webView:didPerformClientRedirectFromURL:toURL:)];
161     m_navigationDelegateMethods.webViewDidCancelClientRedirect = [delegate respondsToSelector:@selector(_webViewDidCancelClientRedirect:)];
162     m_navigationDelegateMethods.webViewNavigationDidFinishDocumentLoad = [delegate respondsToSelector:@selector(_webView:navigationDidFinishDocumentLoad:)];
163     m_navigationDelegateMethods.webViewNavigationDidSameDocumentNavigation = [delegate respondsToSelector:@selector(_webView:navigation:didSameDocumentNavigation:)];
164     m_navigationDelegateMethods.webViewRenderingProgressDidChange = [delegate respondsToSelector:@selector(_webView:renderingProgressDidChange:)];
165     m_navigationDelegateMethods.webViewDidReceiveAuthenticationChallengeCompletionHandler = [delegate respondsToSelector:@selector(webView:didReceiveAuthenticationChallenge:completionHandler:)];
166     m_navigationDelegateMethods.webViewWebContentProcessDidTerminate = [delegate respondsToSelector:@selector(webViewWebContentProcessDidTerminate:)];
167     m_navigationDelegateMethods.webViewWebContentProcessDidTerminateWithReason = [delegate respondsToSelector:@selector(_webView:webContentProcessDidTerminateWithReason:)];
168     m_navigationDelegateMethods.webViewWebProcessDidCrash = [delegate respondsToSelector:@selector(_webViewWebProcessDidCrash:)];
169     m_navigationDelegateMethods.webViewWebProcessDidBecomeResponsive = [delegate respondsToSelector:@selector(_webViewWebProcessDidBecomeResponsive:)];
170     m_navigationDelegateMethods.webViewWebProcessDidBecomeUnresponsive = [delegate respondsToSelector:@selector(_webViewWebProcessDidBecomeUnresponsive:)];
171     m_navigationDelegateMethods.webCryptoMasterKeyForWebView = [delegate respondsToSelector:@selector(_webCryptoMasterKeyForWebView:)];
172     m_navigationDelegateMethods.webViewDidBeginNavigationGesture = [delegate respondsToSelector:@selector(_webViewDidBeginNavigationGesture:)];
173     m_navigationDelegateMethods.webViewWillEndNavigationGestureWithNavigationToBackForwardListItem = [delegate respondsToSelector:@selector(_webViewWillEndNavigationGesture:withNavigationToBackForwardListItem:)];
174     m_navigationDelegateMethods.webViewDidEndNavigationGestureWithNavigationToBackForwardListItem = [delegate respondsToSelector:@selector(_webViewDidEndNavigationGesture:withNavigationToBackForwardListItem:)];
175     m_navigationDelegateMethods.webViewWillSnapshotBackForwardListItem = [delegate respondsToSelector:@selector(_webView:willSnapshotBackForwardListItem:)];
176     m_navigationDelegateMethods.webViewNavigationGestureSnapshotWasRemoved = [delegate respondsToSelector:@selector(_webViewDidRemoveNavigationGestureSnapshot:)];
177     m_navigationDelegateMethods.webViewURLContentRuleListIdentifiersNotifications = [delegate respondsToSelector:@selector(_webView:URL:contentRuleListIdentifiers:notifications:)];
178 #if USE(QUICK_LOOK)
179     m_navigationDelegateMethods.webViewDidStartLoadForQuickLookDocumentInMainFrame = [delegate respondsToSelector:@selector(_webView:didStartLoadForQuickLookDocumentInMainFrameWithFileName:uti:)];
180     m_navigationDelegateMethods.webViewDidFinishLoadForQuickLookDocumentInMainFrame = [delegate respondsToSelector:@selector(_webView:didFinishLoadForQuickLookDocumentInMainFrame:)];
181     m_navigationDelegateMethods.webViewDidRequestPasswordForQuickLookDocument = [delegate respondsToSelector:@selector(_webViewDidRequestPasswordForQuickLookDocument:)];
182 #endif
183 #if PLATFORM(MAC)
184     m_navigationDelegateMethods.webViewWebGLLoadPolicyForURL = [delegate respondsToSelector:@selector(_webView:webGLLoadPolicyForURL:decisionHandler:)];
185     m_navigationDelegateMethods.webViewResolveWebGLLoadPolicyForURL = [delegate respondsToSelector:@selector(_webView:resolveWebGLLoadPolicyForURL:decisionHandler:)];
186     m_navigationDelegateMethods.webViewWillGoToBackForwardListItemInPageCache = [delegate respondsToSelector:@selector(_webView:willGoToBackForwardListItem:inPageCache:)];
187     m_navigationDelegateMethods.webViewDidFailToInitializePlugInWithInfo = [delegate respondsToSelector:@selector(_webView:didFailToInitializePlugInWithInfo:)];
188     m_navigationDelegateMethods.webViewDidBlockInsecurePluginVersionWithInfo = [delegate respondsToSelector:@selector(_webView:didBlockInsecurePluginVersionWithInfo:)];
189     m_navigationDelegateMethods.webViewBackForwardListItemAddedRemoved = [delegate respondsToSelector:@selector(_webView:backForwardListItemAdded:removed:)];
190     m_navigationDelegateMethods.webViewDecidePolicyForPluginLoadWithCurrentPolicyPluginInfoCompletionHandler = [delegate respondsToSelector:@selector(_webView:decidePolicyForPluginLoadWithCurrentPolicy:pluginInfo:completionHandler:)];
191 #endif
192 }
193
194 RetainPtr<id <WKHistoryDelegatePrivate> > NavigationState::historyDelegate()
195 {
196     return m_historyDelegate.get();
197 }
198
199 void NavigationState::setHistoryDelegate(id <WKHistoryDelegatePrivate> historyDelegate)
200 {
201     m_historyDelegate = historyDelegate;
202
203     m_historyDelegateMethods.webViewDidNavigateWithNavigationData = [historyDelegate respondsToSelector:@selector(_webView:didNavigateWithNavigationData:)];
204     m_historyDelegateMethods.webViewDidPerformClientRedirectFromURLToURL = [historyDelegate respondsToSelector:@selector(_webView:didPerformClientRedirectFromURL:toURL:)];
205     m_historyDelegateMethods.webViewDidPerformServerRedirectFromURLToURL = [historyDelegate respondsToSelector:@selector(_webView:didPerformServerRedirectFromURL:toURL:)];
206     m_historyDelegateMethods.webViewDidUpdateHistoryTitleForURL = [historyDelegate respondsToSelector:@selector(_webView:didUpdateHistoryTitle:forURL:)];
207 }
208
209 void NavigationState::navigationGestureDidBegin()
210 {
211     if (!m_navigationDelegateMethods.webViewDidBeginNavigationGesture)
212         return;
213
214     auto navigationDelegate = m_navigationDelegate.get();
215     if (!navigationDelegate)
216         return;
217
218     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webViewDidBeginNavigationGesture:m_webView];
219 }
220
221 void NavigationState::navigationGestureWillEnd(bool willNavigate, WebBackForwardListItem& item)
222 {
223     if (!m_navigationDelegateMethods.webViewWillEndNavigationGestureWithNavigationToBackForwardListItem)
224         return;
225
226     auto navigationDelegate = m_navigationDelegate.get();
227     if (!navigationDelegate)
228         return;
229
230     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webViewWillEndNavigationGesture:m_webView withNavigationToBackForwardListItem:willNavigate ? wrapper(item) : nil];
231 }
232
233 void NavigationState::navigationGestureDidEnd(bool willNavigate, WebBackForwardListItem& item)
234 {
235     if (!m_navigationDelegateMethods.webViewDidEndNavigationGestureWithNavigationToBackForwardListItem)
236         return;
237
238     auto navigationDelegate = m_navigationDelegate.get();
239     if (!navigationDelegate)
240         return;
241
242     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webViewDidEndNavigationGesture:m_webView withNavigationToBackForwardListItem:willNavigate ? wrapper(item) : nil];
243 }
244
245 void NavigationState::willRecordNavigationSnapshot(WebBackForwardListItem& item)
246 {
247     if (!m_navigationDelegateMethods.webViewWillSnapshotBackForwardListItem)
248         return;
249
250     auto navigationDelegate = m_navigationDelegate.get();
251     if (!navigationDelegate)
252         return;
253
254     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webView:m_webView willSnapshotBackForwardListItem:wrapper(item)];
255 }
256
257 void NavigationState::navigationGestureSnapshotWasRemoved()
258 {
259     if (!m_navigationDelegateMethods.webViewNavigationGestureSnapshotWasRemoved)
260         return;
261
262     auto navigationDelegate = m_navigationDelegate.get();
263     if (!navigationDelegate)
264         return;
265
266     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webViewDidRemoveNavigationGestureSnapshot:m_webView];
267 }
268
269 #if USE(QUICK_LOOK)
270 void NavigationState::didRequestPasswordForQuickLookDocument()
271 {
272     if (!m_navigationDelegateMethods.webViewDidRequestPasswordForQuickLookDocument)
273         return;
274
275     auto navigationDelegate = m_navigationDelegate.get();
276     if (!navigationDelegate)
277         return;
278
279     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webViewDidRequestPasswordForQuickLookDocument:m_webView];
280 }
281 #endif
282
283 void NavigationState::didFirstPaint()
284 {
285     if (!m_navigationDelegateMethods.webViewRenderingProgressDidChange)
286         return;
287
288     auto navigationDelegate = m_navigationDelegate.get();
289     if (!navigationDelegate)
290         return;
291
292     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webView:m_webView renderingProgressDidChange:_WKRenderingProgressEventFirstPaint];
293 }
294
295 NavigationState::NavigationClient::NavigationClient(NavigationState& navigationState)
296     : m_navigationState(navigationState)
297 {
298 }
299
300 NavigationState::NavigationClient::~NavigationClient()
301 {
302 }
303
304 #if PLATFORM(MAC)
305 bool NavigationState::NavigationClient::didFailToInitializePlugIn(WebPageProxy&, API::Dictionary& info)
306 {
307     if (!m_navigationState.m_navigationDelegateMethods.webViewDidFailToInitializePlugInWithInfo)
308         return false;
309     
310     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
311     if (!navigationDelegate)
312         return false;
313     
314     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView didFailToInitializePlugInWithInfo:wrapper(info)];
315     return true;
316 }
317
318 bool NavigationState::NavigationClient::didBlockInsecurePluginVersion(WebPageProxy&, API::Dictionary& info)
319 {
320     if (!m_navigationState.m_navigationDelegateMethods.webViewDidBlockInsecurePluginVersionWithInfo)
321         return false;
322
323     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
324     if (!navigationDelegate)
325         return false;
326
327     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView didBlockInsecurePluginVersionWithInfo:wrapper(info)];
328     return true;
329 }
330
331 static WebKit::PluginModuleLoadPolicy pluginModuleLoadPolicy(_WKPluginModuleLoadPolicy policy)
332 {
333     switch (policy) {
334     case _WKPluginModuleLoadPolicyLoadNormally:
335         return WebKit::PluginModuleLoadNormally;
336     case _WKPluginModuleLoadPolicyLoadUnsandboxed:
337         return WebKit::PluginModuleLoadUnsandboxed;
338     case _WKPluginModuleLoadPolicyBlockedForSecurity:
339         return WebKit::PluginModuleBlockedForSecurity;
340     case _WKPluginModuleLoadPolicyBlockedForCompatibility:
341         return WebKit::PluginModuleBlockedForCompatibility;
342     }
343     ASSERT_NOT_REACHED();
344     return WebKit::PluginModuleLoadNormally;
345 }
346
347 static _WKPluginModuleLoadPolicy wkPluginModuleLoadPolicy(WebKit::PluginModuleLoadPolicy policy)
348 {
349     switch (policy) {
350     case WebKit::PluginModuleLoadNormally:
351         return _WKPluginModuleLoadPolicyLoadNormally;
352     case WebKit::PluginModuleLoadUnsandboxed:
353         return _WKPluginModuleLoadPolicyLoadUnsandboxed;
354     case WebKit::PluginModuleBlockedForSecurity:
355         return _WKPluginModuleLoadPolicyBlockedForSecurity;
356     case WebKit::PluginModuleBlockedForCompatibility:
357         return _WKPluginModuleLoadPolicyBlockedForCompatibility;
358     }
359     ASSERT_NOT_REACHED();
360     return _WKPluginModuleLoadPolicyLoadNormally;
361 }
362
363 void NavigationState::NavigationClient::decidePolicyForPluginLoad(WebKit::WebPageProxy&, WebKit::PluginModuleLoadPolicy currentPluginLoadPolicy, API::Dictionary& pluginInformation, CompletionHandler<void(WebKit::PluginModuleLoadPolicy, const String&)>&& completionHandler)
364 {
365     if (!m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForPluginLoadWithCurrentPolicyPluginInfoCompletionHandler) {
366         completionHandler(currentPluginLoadPolicy, { });
367         return;
368     }
369     
370     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
371     if (!navigationDelegate) {
372         completionHandler(currentPluginLoadPolicy, { });
373         return;
374     }
375
376     auto checker = CompletionHandlerCallChecker::create(navigationDelegate.get(), @selector(_webView:decidePolicyForPluginLoadWithCurrentPolicy:pluginInfo:completionHandler:));
377     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView decidePolicyForPluginLoadWithCurrentPolicy:wkPluginModuleLoadPolicy(currentPluginLoadPolicy) pluginInfo:wrapper(pluginInformation) completionHandler:BlockPtr<void(_WKPluginModuleLoadPolicy, NSString *)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](_WKPluginModuleLoadPolicy policy, NSString *unavailabilityDescription) mutable {
378         if (checker->completionHandlerHasBeenCalled())
379             return;
380         checker->didCallCompletionHandler();
381         completionHandler(pluginModuleLoadPolicy(policy), unavailabilityDescription);
382     }).get()];
383 }
384
385 inline WebCore::WebGLLoadPolicy toWebCoreWebGLLoadPolicy(_WKWebGLLoadPolicy policy)
386 {
387     switch (policy) {
388     case _WKWebGLLoadPolicyAllowCreation:
389         return WebCore::WebGLAllowCreation;
390     case _WKWebGLLoadPolicyBlockCreation:
391         return WebCore::WebGLBlockCreation;
392     case _WKWebGLLoadPolicyPendingCreation:
393         return WebCore::WebGLPendingCreation;
394     }
395     
396     ASSERT_NOT_REACHED();
397     return WebCore::WebGLAllowCreation;
398 }
399
400 void NavigationState::NavigationClient::webGLLoadPolicy(WebPageProxy&, const URL& url, CompletionHandler<void(WebCore::WebGLLoadPolicy)>&& completionHandler) const
401 {
402     if (!m_navigationState.m_navigationDelegateMethods.webViewWebGLLoadPolicyForURL) {
403         completionHandler(WebGLAllowCreation);
404         return;
405     }
406
407     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
408     auto checker = CompletionHandlerCallChecker::create(navigationDelegate.get(), @selector(_webView:webGLLoadPolicyForURL:decisionHandler:));
409     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView webGLLoadPolicyForURL:(NSURL *)url decisionHandler:BlockPtr<void(_WKWebGLLoadPolicy)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](_WKWebGLLoadPolicy policy) mutable {
410         if (checker->completionHandlerHasBeenCalled())
411             return;
412         checker->didCallCompletionHandler();
413         completionHandler(toWebCoreWebGLLoadPolicy(policy));
414     }).get()];
415 }
416
417 void NavigationState::NavigationClient::resolveWebGLLoadPolicy(WebPageProxy&, const URL& url, CompletionHandler<void(WebCore::WebGLLoadPolicy)>&& completionHandler) const
418 {
419     if (!m_navigationState.m_navigationDelegateMethods.webViewResolveWebGLLoadPolicyForURL) {
420         completionHandler(WebGLAllowCreation);
421         return;
422     }
423     
424     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
425     auto checker = CompletionHandlerCallChecker::create(navigationDelegate.get(), @selector(_webView:resolveWebGLLoadPolicyForURL:decisionHandler:));
426     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView resolveWebGLLoadPolicyForURL:(NSURL *)url decisionHandler:BlockPtr<void(_WKWebGLLoadPolicy)>::fromCallable([completionHandler = WTFMove(completionHandler), checker = WTFMove(checker)](_WKWebGLLoadPolicy policy) mutable {
427         if (checker->completionHandlerHasBeenCalled())
428             return;
429         checker->didCallCompletionHandler();
430         completionHandler(toWebCoreWebGLLoadPolicy(policy));
431     }).get()];
432 }
433
434 bool NavigationState::NavigationClient::didChangeBackForwardList(WebPageProxy&, WebBackForwardListItem* added, const Vector<Ref<WebBackForwardListItem>>& removed)
435 {
436     if (!m_navigationState.m_navigationDelegateMethods.webViewBackForwardListItemAddedRemoved)
437         return false;
438
439     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
440     if (!navigationDelegate)
441         return false;
442
443     NSMutableArray<WKBackForwardListItem *> *removedItems = nil;
444     if (removed.size()) {
445         removedItems = [[[NSMutableArray alloc] initWithCapacity:removed.size()] autorelease];
446         for (auto& removedItem : removed)
447             [removedItems addObject:wrapper(removedItem.get())];
448     }
449     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView backForwardListItemAdded:wrapper(added) removed:removedItems];
450     return true;
451 }
452
453 bool NavigationState::NavigationClient::willGoToBackForwardListItem(WebPageProxy&, WebBackForwardListItem& item, bool inPageCache)
454 {
455     if (!m_navigationState.m_navigationDelegateMethods.webViewWillGoToBackForwardListItemInPageCache)
456         return false;
457
458     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
459     if (!navigationDelegate)
460         return false;
461
462     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView willGoToBackForwardListItem:wrapper(item) inPageCache:inPageCache];
463     return true;
464 }
465 #endif
466
467 static void tryAppLink(Ref<API::NavigationAction>&& navigationAction, const String& currentMainFrameURL, WTF::Function<void(bool)>&& completionHandler)
468 {
469 #if HAVE(APP_LINKS)
470     if (!navigationAction->shouldOpenAppLinks()) {
471         completionHandler(false);
472         return;
473     }
474
475     auto* localCompletionHandler = new WTF::Function<void (bool)>(WTFMove(completionHandler));
476     [LSAppLink openWithURL:navigationAction->request().url() completionHandler:[localCompletionHandler](BOOL success, NSError *) {
477         dispatch_async(dispatch_get_main_queue(), [localCompletionHandler, success] {
478             (*localCompletionHandler)(success);
479             delete localCompletionHandler;
480         });
481     }];
482 #else
483     completionHandler(false);
484 #endif
485 }
486
487 void NavigationState::NavigationClient::decidePolicyForNavigationAction(WebPageProxy& webPageProxy, Ref<API::NavigationAction>&& navigationAction, Ref<WebFramePolicyListenerProxy>&& listener, API::Object* userInfo)
488 {
489     ASSERT(webPageProxy.mainFrame());
490     String mainFrameURLString = webPageProxy.mainFrame()->url();
491     bool subframeNavigation = navigationAction->targetFrame() && !navigationAction->targetFrame()->isMainFrame();
492
493     if (!m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionDecisionHandler
494         && !m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionDecisionHandlerWebsitePolicies
495         && !m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionUserInfoDecisionHandlerWebsitePolicies) {
496         auto completionHandler = [webPage = makeRef(webPageProxy), listener = WTFMove(listener), navigationAction = navigationAction.copyRef()] (bool followedLinkToApp) {
497             if (followedLinkToApp) {
498                 listener->ignore();
499                 return;
500             }
501
502             if (!navigationAction->targetFrame()) {
503                 listener->use();
504                 return;
505             }
506
507             NSURLRequest *nsURLRequest = wrapper(API::URLRequest::create(navigationAction->request()));
508             if ([NSURLConnection canHandleRequest:nsURLRequest] || webPage->urlSchemeHandlerForScheme([nsURLRequest URL].scheme)) {
509                 if (navigationAction->shouldPerformDownload())
510                     listener->download();
511                 else
512                     listener->use();
513                 return;
514             }
515
516 #if PLATFORM(MAC)
517             // A file URL shouldn't fall through to here, but if it did,
518             // it would be a security risk to open it.
519             if (![[nsURLRequest URL] isFileURL])
520                 [[NSWorkspace sharedWorkspace] openURL:[nsURLRequest URL]];
521 #endif
522             listener->ignore();
523         };
524         tryAppLink(WTFMove(navigationAction), mainFrameURLString, WTFMove(completionHandler));
525         return;
526     }
527
528     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
529     if (!navigationDelegate)
530         return;
531
532     bool delegateHasWebsitePolicies = m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionDecisionHandlerWebsitePolicies || m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionUserInfoDecisionHandlerWebsitePolicies;
533     
534     auto checker = CompletionHandlerCallChecker::create(navigationDelegate.get(), delegateHasWebsitePolicies ? @selector(_webView:decidePolicyForNavigationAction:decisionHandler:) : @selector(webView:decidePolicyForNavigationAction:decisionHandler:));
535     
536     auto decisionHandlerWithPolicies = [localListener = WTFMove(listener), navigationAction = navigationAction.copyRef(), checker = WTFMove(checker), mainFrameURLString, webPageProxy = makeRef(webPageProxy), subframeNavigation](WKNavigationActionPolicy actionPolicy, _WKWebsitePolicies *websitePolicies) mutable {
537         if (checker->completionHandlerHasBeenCalled())
538             return;
539         checker->didCallCompletionHandler();
540
541         RefPtr<API::WebsitePolicies> apiWebsitePolicies = websitePolicies ? websitePolicies->_websitePolicies.get() : nullptr;
542         if (apiWebsitePolicies) {
543             if (auto* websiteDataStore = apiWebsitePolicies->websiteDataStore()) {
544                 auto sessionID = websiteDataStore->websiteDataStore().sessionID();
545                 if (!sessionID.isEphemeral() && sessionID != PAL::SessionID::defaultSessionID())
546                     [NSException raise:NSInvalidArgumentException format:@"_WKWebsitePolicies.websiteDataStore must be nil, default, or non-persistent."];
547                 if (subframeNavigation)
548                     [NSException raise:NSInvalidArgumentException format:@"_WKWebsitePolicies.websiteDataStore must be nil for subframe navigations."];
549             }
550         }
551
552         switch (actionPolicy) {
553         case WKNavigationActionPolicyAllow:
554         case _WKNavigationActionPolicyAllowInNewProcess:
555             tryAppLink(WTFMove(navigationAction), mainFrameURLString, [actionPolicy, localListener = WTFMove(localListener), websitePolicies = WTFMove(apiWebsitePolicies)](bool followedLinkToApp) mutable {
556                 if (followedLinkToApp) {
557                     localListener->ignore();
558                     return;
559                 }
560
561                 localListener->use(websitePolicies.get(), actionPolicy == _WKNavigationActionPolicyAllowInNewProcess ? ProcessSwapRequestedByClient::Yes : ProcessSwapRequestedByClient::No);
562             });
563         
564             break;
565
566         case WKNavigationActionPolicyCancel:
567             localListener->ignore();
568             break;
569
570         case _WKNavigationActionPolicyDownload:
571             localListener->download();
572             break;
573         case _WKNavigationActionPolicyAllowWithoutTryingAppLink:
574             localListener->use(apiWebsitePolicies.get());
575             break;
576         }
577     };
578     
579     if (delegateHasWebsitePolicies) {
580         auto decisionHandler = BlockPtr<void(WKNavigationActionPolicy, _WKWebsitePolicies *)>::fromCallable(WTFMove(decisionHandlerWithPolicies));
581         if (m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationActionUserInfoDecisionHandlerWebsitePolicies)
582             [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView decidePolicyForNavigationAction:wrapper(navigationAction) userInfo:userInfo ? static_cast<id <NSSecureCoding>>(userInfo->wrapper()) : nil decisionHandler:decisionHandler.get()];
583         else {
584             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
585             [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView decidePolicyForNavigationAction:wrapper(navigationAction) decisionHandler:decisionHandler.get()];
586             ALLOW_DEPRECATED_DECLARATIONS_END
587         }
588     } else {
589         auto decisionHandlerWithoutPolicies = [decisionHandlerWithPolicies = WTFMove(decisionHandlerWithPolicies)] (WKNavigationActionPolicy actionPolicy) mutable {
590             decisionHandlerWithPolicies(actionPolicy, nil);
591         };
592         [navigationDelegate webView:m_navigationState.m_webView decidePolicyForNavigationAction:wrapper(navigationAction) decisionHandler:BlockPtr<void(WKNavigationActionPolicy)>::fromCallable(WTFMove(decisionHandlerWithoutPolicies)).get()];
593     }
594 }
595
596 void NavigationState::NavigationClient::contentRuleListNotification(WebPageProxy&, URL&& url, Vector<String>&& listIdentifiers, Vector<String>&& notifications)
597 {
598     if (!m_navigationState.m_navigationDelegateMethods.webViewURLContentRuleListIdentifiersNotifications)
599         return;
600
601     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
602     if (!navigationDelegate)
603         return;
604
605     ASSERT(listIdentifiers.size() == notifications.size());
606
607     auto identifiers = adoptNS([[NSMutableArray alloc] initWithCapacity:listIdentifiers.size()]);
608     for (auto& identifier : listIdentifiers)
609         [identifiers addObject:identifier];
610
611     auto nsNotifications = adoptNS([[NSMutableArray alloc] initWithCapacity:notifications.size()]);
612     for (auto& notification : notifications)
613         [nsNotifications addObject:notification];
614     
615     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView URL:url contentRuleListIdentifiers:identifiers.get() notifications:nsNotifications.get()];
616 }
617     
618 void NavigationState::NavigationClient::decidePolicyForNavigationResponse(WebPageProxy& page, Ref<API::NavigationResponse>&& navigationResponse, Ref<WebFramePolicyListenerProxy>&& listener, API::Object* userData)
619 {
620     if (!m_navigationState.m_navigationDelegateMethods.webViewDecidePolicyForNavigationResponseDecisionHandler) {
621         NSURL *url = navigationResponse->response().nsURLResponse().URL;
622         if ([url isFileURL]) {
623             BOOL isDirectory = NO;
624             BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:url.path isDirectory:&isDirectory];
625
626             if (exists && !isDirectory && navigationResponse->canShowMIMEType())
627                 listener->use();
628             else
629                 listener->ignore();
630             return;
631         }
632
633         if (navigationResponse->canShowMIMEType())
634             listener->use();
635         else
636             listener->ignore();
637         return;
638     }
639
640     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
641     if (!navigationDelegate)
642         return;
643
644     auto checker = CompletionHandlerCallChecker::create(navigationDelegate.get(), @selector(webView:decidePolicyForNavigationResponse:decisionHandler:));
645     [navigationDelegate webView:m_navigationState.m_webView decidePolicyForNavigationResponse:wrapper(navigationResponse) decisionHandler:BlockPtr<void(WKNavigationResponsePolicy)>::fromCallable([localListener = WTFMove(listener), checker = WTFMove(checker)](WKNavigationResponsePolicy responsePolicy) {
646         if (checker->completionHandlerHasBeenCalled())
647             return;
648         checker->didCallCompletionHandler();
649
650         switch (responsePolicy) {
651         case WKNavigationResponsePolicyAllow:
652             localListener->use();
653             break;
654
655         case WKNavigationResponsePolicyCancel:
656             localListener->ignore();
657             break;
658
659         case _WKNavigationResponsePolicyBecomeDownload:
660             localListener->download();
661             break;
662         }
663     }).get()];
664 }
665
666 void NavigationState::NavigationClient::didStartProvisionalNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object* userInfo)
667 {
668     if (!m_navigationState.m_navigationDelegateMethods.webViewDidStartProvisionalNavigation
669         && !m_navigationState.m_navigationDelegateMethods.webViewDidStartProvisionalNavigationUserInfo)
670         return;
671
672     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
673     if (!navigationDelegate)
674         return;
675
676     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
677
678     if (m_navigationState.m_navigationDelegateMethods.webViewDidStartProvisionalNavigationUserInfo)
679         [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView didStartProvisionalNavigation:wrapper(navigation) userInfo:userInfo ? static_cast<id <NSSecureCoding>>(userInfo->wrapper()) : nil];
680     else
681         [navigationDelegate webView:m_navigationState.m_webView didStartProvisionalNavigation:wrapper(navigation)];
682 }
683
684 void NavigationState::NavigationClient::didReceiveServerRedirectForProvisionalNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object*)
685 {
686     if (!m_navigationState.m_navigationDelegateMethods.webViewDidReceiveServerRedirectForProvisionalNavigation)
687         return;
688
689     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
690     if (!navigationDelegate)
691         return;
692
693     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
694
695     [navigationDelegate webView:m_navigationState.m_webView didReceiveServerRedirectForProvisionalNavigation:wrapper(navigation)];
696 }
697
698 void NavigationState::NavigationClient::willPerformClientRedirect(WebPageProxy& page, const WTF::String& urlString, double delay)
699 {
700     if (!m_navigationState.m_navigationDelegateMethods.webViewWillPerformClientRedirect)
701         return;
702
703     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
704     if (!navigationDelegate)
705         return;
706
707     URL url(URL(), urlString);
708
709     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webView:m_navigationState.m_webView willPerformClientRedirectToURL:url delay:delay];
710 }
711
712 void NavigationState::NavigationClient::didPerformClientRedirect(WebPageProxy& page, const WTF::String& sourceURLString, const WTF::String& destinationURLString)
713 {
714     if (!m_navigationState.m_navigationDelegateMethods.webViewDidPerformClientRedirect)
715         return;
716
717     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
718     if (!navigationDelegate)
719         return;
720
721     URL sourceURL(URL(), sourceURLString);
722     URL destinationURL(URL(), destinationURLString);
723
724     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webView:m_navigationState.m_webView didPerformClientRedirectFromURL:sourceURL toURL:destinationURL];
725 }
726
727 void NavigationState::NavigationClient::didCancelClientRedirect(WebPageProxy& page)
728 {
729     if (!m_navigationState.m_navigationDelegateMethods.webViewDidCancelClientRedirect)
730         return;
731
732     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
733     if (!navigationDelegate)
734         return;
735
736     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate) _webViewDidCancelClientRedirect:m_navigationState.m_webView];
737 }
738
739 static RetainPtr<NSError> createErrorWithRecoveryAttempter(WKWebView *webView, WebFrameProxy& webFrameProxy, NSError *originalError)
740 {
741     RefPtr<API::FrameHandle> frameHandle = API::FrameHandle::create(webFrameProxy.frameID());
742
743     auto recoveryAttempter = adoptNS([[WKReloadFrameErrorRecoveryAttempter alloc] initWithWebView:webView frameHandle:wrapper(*frameHandle) urlString:originalError.userInfo[NSURLErrorFailingURLStringErrorKey]]);
744
745     auto userInfo = adoptNS([[NSMutableDictionary alloc] initWithObjectsAndKeys:recoveryAttempter.get(), _WKRecoveryAttempterErrorKey, nil]);
746
747     if (NSDictionary *originalUserInfo = originalError.userInfo)
748         [userInfo addEntriesFromDictionary:originalUserInfo];
749
750     return adoptNS([[NSError alloc] initWithDomain:originalError.domain code:originalError.code userInfo:userInfo.get()]);
751 }
752
753 // FIXME: Shouldn't need to pass the WebFrameProxy in here. At most, a FrameHandle.
754 void NavigationState::NavigationClient::didFailProvisionalNavigationWithError(WebPageProxy& page, WebFrameProxy& webFrameProxy, API::Navigation* navigation, const WebCore::ResourceError& error, API::Object*)
755 {
756     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
757
758     // FIXME: Set the error on the navigation object.
759
760     if (!m_navigationState.m_navigationDelegateMethods.webViewDidFailProvisionalNavigationWithError)
761         return;
762
763     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
764     if (!navigationDelegate)
765         return;
766
767     auto errorWithRecoveryAttempter = createErrorWithRecoveryAttempter(m_navigationState.m_webView, webFrameProxy, error);
768     [navigationDelegate webView:m_navigationState.m_webView didFailProvisionalNavigation:wrapper(navigation) withError:errorWithRecoveryAttempter.get()];
769 }
770
771 // FIXME: Shouldn't need to pass the WebFrameProxy in here. At most, a FrameHandle.
772 void NavigationState::NavigationClient::didFailProvisionalLoadInSubframeWithError(WebPageProxy& page, WebFrameProxy& webFrameProxy, const SecurityOriginData& securityOrigin, API::Navigation*, const WebCore::ResourceError& error, API::Object*)
773 {
774     // FIXME: We should assert that navigation is not null here, but it's currently null because WebPageProxy::didFailProvisionalLoadForFrame passes null.
775
776     if (!m_navigationState.m_navigationDelegateMethods.webViewNavigationDidFailProvisionalLoadInSubframeWithError)
777         return;
778
779     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
780     auto errorWithRecoveryAttempter = createErrorWithRecoveryAttempter(m_navigationState.m_webView, webFrameProxy, error);
781
782     [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView navigation:nil didFailProvisionalLoadInSubframe:wrapper(API::FrameInfo::create(webFrameProxy, securityOrigin.securityOrigin())) withError:errorWithRecoveryAttempter.get()];
783 }
784
785 void NavigationState::NavigationClient::didCommitNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object*)
786 {
787     if (!m_navigationState.m_navigationDelegateMethods.webViewDidCommitNavigation)
788         return;
789
790     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
791     if (!navigationDelegate)
792         return;
793
794     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
795
796     [navigationDelegate webView:m_navigationState.m_webView didCommitNavigation:wrapper(navigation)];
797 }
798
799 void NavigationState::NavigationClient::didFinishDocumentLoad(WebPageProxy& page, API::Navigation* navigation, API::Object*)
800 {
801     if (!m_navigationState.m_navigationDelegateMethods.webViewNavigationDidFinishDocumentLoad)
802         return;
803
804     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
805     if (!navigationDelegate)
806         return;
807
808     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
809
810     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState.m_webView navigationDidFinishDocumentLoad:wrapper(navigation)];
811 }
812
813 void NavigationState::NavigationClient::didFinishNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object*)
814 {
815     if (!m_navigationState.m_navigationDelegateMethods.webViewDidFinishNavigation)
816         return;
817
818     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
819     if (!navigationDelegate)
820         return;
821
822     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
823
824     [navigationDelegate webView:m_navigationState.m_webView didFinishNavigation:wrapper(navigation)];
825 }
826
827 // FIXME: Shouldn't need to pass the WebFrameProxy in here. At most, a FrameHandle.
828 void NavigationState::NavigationClient::didFailNavigationWithError(WebPageProxy& page, WebFrameProxy& webFrameProxy, API::Navigation* navigation, const WebCore::ResourceError& error, API::Object* userInfo)
829 {
830     if (!m_navigationState.m_navigationDelegateMethods.webViewDidFailNavigationWithError
831         && !m_navigationState.m_navigationDelegateMethods.webViewDidFailNavigationWithErrorUserInfo)
832         return;
833
834     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
835     if (!navigationDelegate)
836         return;
837
838     // FIXME: We should assert that navigation is not null here, but it's currently null for some navigations through the page cache.
839
840     auto errorWithRecoveryAttempter = createErrorWithRecoveryAttempter(m_navigationState.m_webView, webFrameProxy, error);
841     if (m_navigationState.m_navigationDelegateMethods.webViewDidFailNavigationWithErrorUserInfo)
842         [(id <WKNavigationDelegatePrivate>)navigationDelegate _webView:m_navigationState.m_webView didFailNavigation:wrapper(navigation) withError:errorWithRecoveryAttempter.get() userInfo:userInfo ? static_cast<id <NSSecureCoding>>(userInfo->wrapper()) : nil];
843     else
844         [navigationDelegate webView:m_navigationState.m_webView didFailNavigation:wrapper(navigation) withError:errorWithRecoveryAttempter.get()];
845 }
846
847 void NavigationState::NavigationClient::didSameDocumentNavigation(WebPageProxy&, API::Navigation* navigation, SameDocumentNavigationType navigationType, API::Object*)
848 {
849     if (!m_navigationState.m_navigationDelegateMethods.webViewNavigationDidSameDocumentNavigation)
850         return;
851
852     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
853     if (!navigationDelegate)
854         return;
855
856     // FIXME: We should assert that navigationID is not zero here, but it's currently zero for some navigations through the page cache.
857
858     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState.m_webView navigation:wrapper(navigation) didSameDocumentNavigation:toWKSameDocumentNavigationType(navigationType)];
859 }
860
861 void NavigationState::NavigationClient::renderingProgressDidChange(WebPageProxy&, OptionSet<WebCore::LayoutMilestone> layoutMilestones)
862 {
863     if (!m_navigationState.m_navigationDelegateMethods.webViewRenderingProgressDidChange)
864         return;
865
866     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
867     if (!navigationDelegate)
868         return;
869
870     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState.m_webView renderingProgressDidChange:renderingProgressEvents(layoutMilestones)];
871 }
872
873 static AuthenticationChallengeDisposition toAuthenticationChallengeDisposition(NSURLSessionAuthChallengeDisposition disposition)
874 {
875     switch (disposition) {
876     case NSURLSessionAuthChallengeUseCredential:
877         return AuthenticationChallengeDisposition::UseCredential;
878     case NSURLSessionAuthChallengePerformDefaultHandling:
879         return AuthenticationChallengeDisposition::PerformDefaultHandling;
880     case NSURLSessionAuthChallengeCancelAuthenticationChallenge:
881         return AuthenticationChallengeDisposition::Cancel;
882     case NSURLSessionAuthChallengeRejectProtectionSpace:
883         return AuthenticationChallengeDisposition::RejectProtectionSpaceAndContinue;
884     }
885     [NSException raise:NSInvalidArgumentException format:@"Invalid NSURLSessionAuthChallengeDisposition (%ld)", (long)disposition];
886 }
887     
888 void NavigationState::NavigationClient::didReceiveAuthenticationChallenge(WebPageProxy&, AuthenticationChallengeProxy& authenticationChallenge)
889 {
890     if (!m_navigationState.m_navigationDelegateMethods.webViewDidReceiveAuthenticationChallengeCompletionHandler)
891         return authenticationChallenge.listener().completeChallenge(WebKit::AuthenticationChallengeDisposition::PerformDefaultHandling);
892
893     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
894     if (!navigationDelegate)
895         return authenticationChallenge.listener().completeChallenge(WebKit::AuthenticationChallengeDisposition::PerformDefaultHandling);
896
897     auto checker = CompletionHandlerCallChecker::create(navigationDelegate.get(), @selector(webView:didReceiveAuthenticationChallenge:completionHandler:));
898     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) webView:m_navigationState.m_webView didReceiveAuthenticationChallenge:wrapper(authenticationChallenge) completionHandler:BlockPtr<void(NSURLSessionAuthChallengeDisposition, NSURLCredential *)>::fromCallable([challenge = makeRef(authenticationChallenge), checker = WTFMove(checker)](NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential) {
899         if (checker->completionHandlerHasBeenCalled())
900             return;
901         checker->didCallCompletionHandler();
902         challenge->listener().completeChallenge(toAuthenticationChallengeDisposition(disposition), Credential(credential));
903     }).get()];
904 }
905
906 static _WKProcessTerminationReason wkProcessTerminationReason(ProcessTerminationReason reason)
907 {
908     switch (reason) {
909     case ProcessTerminationReason::ExceededMemoryLimit:
910         return _WKProcessTerminationReasonExceededMemoryLimit;
911     case ProcessTerminationReason::ExceededCPULimit:
912         return _WKProcessTerminationReasonExceededCPULimit;
913     case ProcessTerminationReason::NavigationSwap:
914         // We probably shouldn't bother coming up with a new API type for process-swapping.
915         // "Requested by client" seems like the best match for existing types.
916         FALLTHROUGH;
917     case ProcessTerminationReason::RequestedByClient:
918         return _WKProcessTerminationReasonRequestedByClient;
919     case ProcessTerminationReason::Crash:
920         return _WKProcessTerminationReasonCrash;
921     }
922     ASSERT_NOT_REACHED();
923     return _WKProcessTerminationReasonCrash;
924 }
925
926 bool NavigationState::NavigationClient::processDidTerminate(WebPageProxy& page, ProcessTerminationReason reason)
927 {
928     if (!m_navigationState.m_navigationDelegateMethods.webViewWebContentProcessDidTerminate
929         && !m_navigationState.m_navigationDelegateMethods.webViewWebContentProcessDidTerminateWithReason
930         && !m_navigationState.m_navigationDelegateMethods.webViewWebProcessDidCrash)
931         return false;
932
933     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
934     if (!navigationDelegate)
935         return false;
936
937     if (m_navigationState.m_navigationDelegateMethods.webViewWebContentProcessDidTerminateWithReason) {
938         [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState.m_webView webContentProcessDidTerminateWithReason:wkProcessTerminationReason(reason)];
939         return true;
940     }
941
942     // We prefer webViewWebContentProcessDidTerminate: over _webViewWebProcessDidCrash:.
943     if (m_navigationState.m_navigationDelegateMethods.webViewWebContentProcessDidTerminate) {
944         [navigationDelegate webViewWebContentProcessDidTerminate:m_navigationState.m_webView];
945         return true;
946     }
947
948     ASSERT(m_navigationState.m_navigationDelegateMethods.webViewWebProcessDidCrash);
949     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webViewWebProcessDidCrash:m_navigationState.m_webView];
950     return true;
951 }
952
953 void NavigationState::NavigationClient::processDidBecomeResponsive(WebPageProxy& page)
954 {
955     if (!m_navigationState.m_navigationDelegateMethods.webViewWebProcessDidBecomeResponsive)
956         return;
957
958     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
959     if (!navigationDelegate)
960         return;
961
962     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webViewWebProcessDidBecomeResponsive:m_navigationState.m_webView];
963 }
964
965 void NavigationState::NavigationClient::processDidBecomeUnresponsive(WebPageProxy& page)
966 {
967     if (!m_navigationState.m_navigationDelegateMethods.webViewWebProcessDidBecomeUnresponsive)
968         return;
969
970     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
971     if (!navigationDelegate)
972         return;
973
974     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webViewWebProcessDidBecomeUnresponsive:m_navigationState.m_webView];
975 }
976
977 RefPtr<API::Data> NavigationState::NavigationClient::webCryptoMasterKey(WebPageProxy&)
978 {
979     if (!m_navigationState.m_navigationDelegateMethods.webCryptoMasterKeyForWebView) {
980         Vector<uint8_t> masterKey;
981         if (!getDefaultWebCryptoMasterKey(masterKey))
982             return nullptr;
983
984         return API::Data::create(masterKey.data(), masterKey.size());
985     }
986
987     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
988     if (!navigationDelegate)
989         return nullptr;
990
991     NSData *data = [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webCryptoMasterKeyForWebView:m_navigationState.m_webView];
992     return API::Data::createWithoutCopying(data);
993 }
994
995 RefPtr<API::String> NavigationState::NavigationClient::signedPublicKeyAndChallengeString(WebPageProxy& page, unsigned keySizeIndex, const RefPtr<API::String>& challengeString, const URL& url)
996 {
997     // WebKitTestRunner uses C API. Hence, no SPI is provided to override the following function.
998     return API::String::create(WebCore::signedPublicKeyAndChallengeString(keySizeIndex, challengeString->string(), url));
999 }
1000
1001 #if USE(QUICK_LOOK)
1002 void NavigationState::NavigationClient::didStartLoadForQuickLookDocumentInMainFrame(const String& fileName, const String& uti)
1003 {
1004     if (!m_navigationState.m_navigationDelegateMethods.webViewDidStartLoadForQuickLookDocumentInMainFrame)
1005         return;
1006
1007     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
1008     if (!navigationDelegate)
1009         return;
1010
1011     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState.m_webView didStartLoadForQuickLookDocumentInMainFrameWithFileName:fileName uti:uti];
1012 }
1013
1014 void NavigationState::NavigationClient::didFinishLoadForQuickLookDocumentInMainFrame(const QuickLookDocumentData& data)
1015 {
1016     if (!m_navigationState.m_navigationDelegateMethods.webViewDidFinishLoadForQuickLookDocumentInMainFrame)
1017         return;
1018
1019     auto navigationDelegate = m_navigationState.m_navigationDelegate.get();
1020     if (!navigationDelegate)
1021         return;
1022
1023     [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState.m_webView didFinishLoadForQuickLookDocumentInMainFrame:(NSData *)data.decodedData()];
1024 }
1025 #endif
1026
1027 // HistoryDelegatePrivate support
1028     
1029 NavigationState::HistoryClient::HistoryClient(NavigationState& navigationState)
1030     : m_navigationState(navigationState)
1031 {
1032 }
1033
1034 NavigationState::HistoryClient::~HistoryClient()
1035 {
1036 }
1037
1038 void NavigationState::HistoryClient::didNavigateWithNavigationData(WebPageProxy&, const WebNavigationDataStore& navigationDataStore)
1039 {
1040     if (!m_navigationState.m_historyDelegateMethods.webViewDidNavigateWithNavigationData)
1041         return;
1042
1043     auto historyDelegate = m_navigationState.m_historyDelegate.get();
1044     if (!historyDelegate)
1045         return;
1046
1047     [historyDelegate _webView:m_navigationState.m_webView didNavigateWithNavigationData:wrapper(API::NavigationData::create(navigationDataStore))];
1048 }
1049
1050 void NavigationState::HistoryClient::didPerformClientRedirect(WebPageProxy&, const WTF::String& sourceURL, const WTF::String& destinationURL)
1051 {
1052     if (!m_navigationState.m_historyDelegateMethods.webViewDidPerformClientRedirectFromURLToURL)
1053         return;
1054
1055     auto historyDelegate = m_navigationState.m_historyDelegate.get();
1056     if (!historyDelegate)
1057         return;
1058
1059     [historyDelegate _webView:m_navigationState.m_webView didPerformClientRedirectFromURL:[NSURL _web_URLWithWTFString:sourceURL] toURL:[NSURL _web_URLWithWTFString:destinationURL]];
1060 }
1061
1062 void NavigationState::HistoryClient::didPerformServerRedirect(WebPageProxy&, const WTF::String& sourceURL, const WTF::String& destinationURL)
1063 {
1064     if (!m_navigationState.m_historyDelegateMethods.webViewDidPerformServerRedirectFromURLToURL)
1065         return;
1066
1067     auto historyDelegate = m_navigationState.m_historyDelegate.get();
1068     if (!historyDelegate)
1069         return;
1070
1071     [historyDelegate _webView:m_navigationState.m_webView didPerformServerRedirectFromURL:[NSURL _web_URLWithWTFString:sourceURL] toURL:[NSURL _web_URLWithWTFString:destinationURL]];
1072 }
1073
1074 void NavigationState::HistoryClient::didUpdateHistoryTitle(WebPageProxy&, const WTF::String& title, const WTF::String& url)
1075 {
1076     if (!m_navigationState.m_historyDelegateMethods.webViewDidUpdateHistoryTitleForURL)
1077         return;
1078
1079     auto historyDelegate = m_navigationState.m_historyDelegate.get();
1080     if (!historyDelegate)
1081         return;
1082
1083     [historyDelegate _webView:m_navigationState.m_webView didUpdateHistoryTitle:title forURL:[NSURL _web_URLWithWTFString:url]];
1084 }
1085
1086 void NavigationState::willChangeIsLoading()
1087 {
1088     [m_webView willChangeValueForKey:@"loading"];
1089 }
1090
1091 #if PLATFORM(IOS_FAMILY)
1092 void NavigationState::releaseNetworkActivityToken(NetworkActivityTokenReleaseReason reason)
1093 {
1094     if (!m_activityToken)
1095         return;
1096
1097     switch (reason) {
1098     case NetworkActivityTokenReleaseReason::LoadCompleted:
1099         RELEASE_LOG_IF(m_webView->_page->isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p NavigationState is releasing background process assertion because a page load completed", this);
1100         break;
1101     case NetworkActivityTokenReleaseReason::ScreenLocked:
1102         RELEASE_LOG_IF(m_webView->_page->isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p NavigationState is releasing background process assertion because the screen was locked", this);
1103         break;
1104     }
1105     m_activityToken = nullptr;
1106     m_releaseActivityTimer.stop();
1107 }
1108 #endif
1109
1110 void NavigationState::didChangeIsLoading()
1111 {
1112 #if PLATFORM(IOS_FAMILY)
1113     if (m_webView->_page->pageLoadState().isLoading()) {
1114         // We do not take a network activity token if a load starts after the screen has been locked.
1115         if ([UIApp isSuspendedUnderLock])
1116             return;
1117
1118         if (m_releaseActivityTimer.isActive()) {
1119             RELEASE_LOG_IF(m_webView->_page->isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NavigationState keeps its process network assertion because a new page load started", this);
1120             m_releaseActivityTimer.stop();
1121         }
1122         if (!m_activityToken) {
1123             RELEASE_LOG_IF(m_webView->_page->isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NavigationState is taking a process network assertion because a page load started", this);
1124             m_activityToken = m_webView->_page->process().throttler().backgroundActivityToken();
1125         }
1126     } else if (m_activityToken) {
1127         // The application is visible so we delay releasing the background activity for 3 seconds to give it a chance to start another navigation
1128         // before suspending the WebContent process <rdar://problem/27910964>.
1129         RELEASE_LOG_IF(m_webView->_page->isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NavigationState will release its process network assertion soon because the page load completed", this);
1130         m_releaseActivityTimer.startOneShot(3_s);
1131     }
1132 #endif
1133
1134     [m_webView didChangeValueForKey:@"loading"];
1135 }
1136
1137 void NavigationState::willChangeTitle()
1138 {
1139     [m_webView willChangeValueForKey:@"title"];
1140 }
1141
1142 void NavigationState::didChangeTitle()
1143 {
1144     [m_webView didChangeValueForKey:@"title"];
1145 }
1146
1147 void NavigationState::willChangeActiveURL()
1148 {
1149     [m_webView willChangeValueForKey:@"URL"];
1150 }
1151
1152 void NavigationState::didChangeActiveURL()
1153 {
1154     [m_webView didChangeValueForKey:@"URL"];
1155 }
1156
1157 void NavigationState::willChangeHasOnlySecureContent()
1158 {
1159     [m_webView willChangeValueForKey:@"hasOnlySecureContent"];
1160 }
1161
1162 void NavigationState::didChangeHasOnlySecureContent()
1163 {
1164     [m_webView didChangeValueForKey:@"hasOnlySecureContent"];
1165 }
1166
1167 void NavigationState::willChangeEstimatedProgress()
1168 {
1169     [m_webView willChangeValueForKey:@"estimatedProgress"];
1170 }
1171
1172 void NavigationState::didChangeEstimatedProgress()
1173 {
1174     [m_webView didChangeValueForKey:@"estimatedProgress"];
1175 }
1176
1177 void NavigationState::willChangeCanGoBack()
1178 {
1179     [m_webView willChangeValueForKey:@"canGoBack"];
1180 }
1181
1182 void NavigationState::didChangeCanGoBack()
1183 {
1184     [m_webView didChangeValueForKey:@"canGoBack"];
1185 }
1186
1187 void NavigationState::willChangeCanGoForward()
1188 {
1189     [m_webView willChangeValueForKey:@"canGoForward"];
1190 }
1191
1192 void NavigationState::didChangeCanGoForward()
1193 {
1194     [m_webView didChangeValueForKey:@"canGoForward"];
1195 }
1196
1197 void NavigationState::willChangeNetworkRequestsInProgress()
1198 {
1199     [m_webView willChangeValueForKey:@"_networkRequestsInProgress"];
1200 }
1201
1202 void NavigationState::didChangeNetworkRequestsInProgress()
1203 {
1204     [m_webView didChangeValueForKey:@"_networkRequestsInProgress"];
1205 }
1206
1207 void NavigationState::willChangeCertificateInfo()
1208 {
1209     [m_webView willChangeValueForKey:@"serverTrust"];
1210     [m_webView willChangeValueForKey:@"certificateChain"];
1211 }
1212
1213 void NavigationState::didChangeCertificateInfo()
1214 {
1215     [m_webView didChangeValueForKey:@"certificateChain"];
1216     [m_webView didChangeValueForKey:@"serverTrust"];
1217 }
1218
1219 void NavigationState::willChangeWebProcessIsResponsive()
1220 {
1221     [m_webView willChangeValueForKey:@"_webProcessIsResponsive"];
1222 }
1223
1224 void NavigationState::didChangeWebProcessIsResponsive()
1225 {
1226     [m_webView didChangeValueForKey:@"_webProcessIsResponsive"];
1227 }
1228
1229 } // namespace WebKit
1230
1231 #endif