-
Notifications
You must be signed in to change notification settings - Fork 26
/
DistributedNavigationDelegate.swift
970 lines (817 loc) · 46.3 KB
/
DistributedNavigationDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//
// DistributedNavigationDelegate.swift
//
// Copyright © 2022 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Common
import Foundation
import WebKit
public final class DistributedNavigationDelegate: NSObject {
internal var responders = ResponderChain()
private var customDelegateMethodHandlers = [Selector: any AnyResponderRef]()
private let getLog: () -> OSLog
private var log: OSLog {
getLog()
}
/// approved navigation before `navigationDidStart` event received (useful for authentication challenge and redirect events)
@MainActor
private var navigationExpectedToStart: Navigation? {
didSet {
updateCurrentNavigation()
}
}
// currently processed NavigationAction decision Task
private var navigationActionDecisionTask: Task<Void, Never>? {
willSet {
navigationActionDecisionTask?.cancel()
}
}
/// ongoing Main Frame navigation (after `navigationDidStart` event received)
@MainActor
private var startedNavigation: Navigation? {
willSet {
startedNavigation?.didResignCurrent()
}
didSet {
updateCurrentNavigation()
}
}
/// published "current" navigation - represents either started or approved (expected to start) navigation
@Published public private(set) var currentNavigation: Navigation?
@MainActor
private func updateCurrentNavigation() {
let currentNavigation = startedNavigation ?? navigationExpectedToStart
guard self.currentNavigation !== currentNavigation else { return }
self.currentNavigation = currentNavigation
}
#if PRIVATE_NAVIGATION_DID_FINISH_CALLBACKS_ENABLED
/// last BackForwardList item committed into WebView
@Published public private(set) var currentHistoryItemIdentity: HistoryItemIdentity?
private func updateCurrentHistoryItemIdentity(_ currentItem: WKBackForwardListItem?) {
guard let identity = currentItem?.identity,
currentHistoryItemIdentity != identity
else { return }
currentHistoryItemIdentity = identity
}
#else
private var currentHistoryItemIdentity: HistoryItemIdentity? { nil }
#endif
public init(log: @escaping @autoclosure () -> OSLog) {
dispatchPrecondition(condition: .onQueue(.main))
self.getLog = log
#if !_MAIN_FRAME_NAVIGATION_ENABLED
_=WKWebView.swizzleLoadMethodOnce
#endif
_=WKNavigationAction.swizzleRequestOnce
}
/** set responder chain for Navigation Events with defined ownership and nullability:
```
navigationDelegate.setResponders( .weak(responder1), .weak(nullable: responder2), .strong(responder3), .strong(nullable: responder4))
```
**/
public func setResponders(_ refs: ResponderRefMaker?...) {
dispatchPrecondition(condition: .onQueue(.main))
responders.setResponders(refs.compactMap { $0 })
}
}
private extension DistributedNavigationDelegate {
#if DEBUG
static var sigIntRaisedForResponders = Set<String>()
#endif
// swiftlint:disable function_parameter_count
/// continues until first non-nil Navigation Responder decision and returned to the `completion` callback
func makeAsyncDecision<T>(for actionDebugInfo: some CustomDebugStringConvertible,
boundToLifetimeOf webView: WKWebView,
with responders: ResponderChain,
decide: @escaping @MainActor (NavigationResponder) async -> T?,
completion: @escaping @MainActor (T?) -> Void,
cancellation: @escaping @MainActor () -> Void) -> Task<Void, Never> {
dispatchPrecondition(condition: .onQueue(.main))
// cancel the decision making Task if WebView deallocates before it‘s finished
let webViewDeinitObserver = webView.deinitObservers.insert(NSObject.DeinitObserver()).memberAfterInsert
let webViewDebugRef = Unmanaged.passUnretained(webView).toOpaque()
// TO DO: ideally the Task should be executed synchronously until the first await, check it later when custom Executors arrive to Swift
let task = Task.detached { @MainActor [responders, weak webView, weak webViewDeinitObserver] in
await withTaskCancellationHandler {
for responder in responders {
// in case of the Task cancellation completion handler will be called in `onCancel:`
guard !Task.isCancelled else { return }
#if DEBUG
let longDecisionMakingCheckCancellable = Self.checkLongDecisionMaking(performedBy: responder) {
"<WKWebView: \(webViewDebugRef.hexValue)>: " + actionDebugInfo.debugDescription
}
defer {
longDecisionMakingCheckCancellable?.cancel()
}
#endif
// complete if responder returns non-nil (non-`.next`) decision
if let decision = await decide(responder) {
guard !Task.isCancelled else { return }
completion(decision)
return
}
}
// default completion handler if none of responders returned non-nil result
guard !Task.isCancelled else { return }
completion(nil)
} onCancel: {
DispatchQueue.main.async {
cancellation()
}
}
// remove WebView deallocation observer on the Task completion
if let webViewDeinitObserver {
webViewDeinitObserver.disarm()
webView?.deinitObservers.remove(webViewDeinitObserver)
}
}
// cancel the Task if WebView deallocates before it‘s finished
webViewDeinitObserver.onDeinit { [log] in
os_log("cancelling \(actionDebugInfo.debugDescription) decision making due to <WKWebView: \(webViewDebugRef.hexValue)> deallocation", log: log, type: .error)
task.cancel()
}
return task
}
// swiftlint:enable function_parameter_count
func makeAsyncDecision<T>(for actionDebugInfo: some CustomDebugStringConvertible,
boundToLifetimeOf webView: WKWebView,
with responders: ResponderChain,
decide: @escaping @MainActor (NavigationResponder) async -> T?,
completion: @escaping @MainActor (T?) -> Void) {
_=makeAsyncDecision(for: actionDebugInfo, boundToLifetimeOf: webView, with: responders, decide: decide, completion: completion, cancellation: { @MainActor in
completion(nil)
})
}
#if DEBUG
/// DEBUG check raising SIGINT (break) if NavigationResponder decision making takes more than 4 seconds
/// the check won‘t be made if `responder.shouldDisableLongDecisionMakingChecks` returns `true`
@MainActor
static func checkLongDecisionMaking<Responder: NavigationResponder>(performedBy responder: Responder, debugDescription: @escaping () -> String) -> AnyCancellable? {
let typeOfResponder = String(describing: Responder.self)
var timeoutWorkItem: DispatchWorkItem?
if !Self.sigIntRaisedForResponders.contains(typeOfResponder),
// class-type responder will be queried for shouldDisableLongDecisionMakingChecks after delay
(responder as? NavigationResponder & AnyObject) != nil
// struct-type can‘t be mutated so it should have shouldDisableLongDecisionMakingChecks set permanently if its decisions take long
|| !responder.shouldDisableLongDecisionMakingChecks {
let responder = responder as? NavigationResponder & AnyObject
timeoutWorkItem = DispatchWorkItem { [weak responder] in
guard responder?.shouldDisableLongDecisionMakingChecks != true else { return }
Self.sigIntRaisedForResponders.insert(typeOfResponder)
breakByRaisingSigInt("""
Decision making for \(debugDescription())
is taking longer than expected.
This may be indicating that there‘s a leak in \(typeOfResponder) Navigation Responder.
Implement `var shouldDisableLongDecisionMakingChecks: Bool` and set it to `true`
for known long decision making to disable this warning.
""")
}
}
if let timeoutWorkItem {
DispatchQueue.main.asyncAfter(deadline: .now() + 4.0, execute: timeoutWorkItem)
return AnyCancellable {
timeoutWorkItem.cancel()
}
}
return nil
}
#endif
/// Instantiates a new Navigation object for a NavigationAction
/// or returns an ExpectedNavigation instance for navigations initiated using Navigator
/// or returns ongoing Navigation for server redirects
/// Maps `WKNavigationAction` to `NavigationAction` according to an active server redirect or an expected NavigationType
@MainActor
func navigation(for wkNavigationAction: WKNavigationAction, in webView: WKWebView) -> Navigation? {
guard wkNavigationAction.targetFrame?.isMainFrame == true else {
return nil
}
// only handled for main-frame navigations:
// get WKNavigation associated with the WKNavigationAction
// it is not `current` yet, unless it‘s a server-redirect
#if _MAIN_FRAME_NAVIGATION_ENABLED
let wkNavigation = wkNavigationAction.mainFrameNavigation
#else
let wkNavigation = webView.expectedMainFrameNavigation(for: wkNavigationAction)
#endif
let navigation: Navigation = {
if let navigation = wkNavigation?.navigation,
// same-document NavigationActions have a previous WKNavigation mainFrameNavigation
!wkNavigationAction.isSameDocumentNavigation {
// it‘s a server-redirect or a developer-initiated navigation, so the WKNavigation already has an associated Navigation object
return navigation
// server-redirected navigation continues with the same WKNavigation identity
} else if let startedNavigation,
case .started = startedNavigation.state,
// redirect Navigation Action should always have sourceFrame set:
// https://github.com/WebKit/WebKit/blob/c39358705b79ccf2da3b76a8be6334e7e3dfcfa6/Source/WebKit/UIProcess/WebPageProxy.cpp#L5675
wkNavigationAction.safeSourceFrame != nil,
wkNavigationAction.isRedirect != false {
return startedNavigation
}
return Navigation(identity: NavigationIdentity(wkNavigation), responders: responders, state: .expected(nil), isCurrent: false)
}()
// wkNavigation.navigation = navigation
if wkNavigation?.navigation == nil {
navigation.associate(with: wkNavigation)
}
// custom NavigationType for navigations with developer-set NavigationType
var navigationType: NavigationType? = navigation.state.expectedNavigationType
var redirectHistory: [NavigationAction]?
// server redirect received
if startedNavigation === navigation {
assert(navigationType == nil)
navigationType = .redirect(.server)
redirectHistory = navigation.navigationActions
// client redirect
} else if let startedNavigation,
// previous navigation completion is delayed until the WKNavigationAction is handled
case .willPerformClientRedirect(delay: let delay) = startedNavigation.state,
// new navigations are started for client redirects
startedNavigation.identity != navigation.identity {
// user-initiated actions aren‘t client redirects
if wkNavigationAction.isUserInitiated != true {
navigationType = .redirect(.client(delay: delay))
redirectHistory = startedNavigation.navigationActions
} else {
startedNavigation.didCancelClientRedirect()
}
}
let navigationAction = NavigationAction(webView: webView, navigationAction: wkNavigationAction, currentHistoryItemIdentity: currentHistoryItemIdentity, redirectHistory: redirectHistory, navigationType: navigationType, mainFrameNavigation: navigation)
navigation.navigationActionReceived(navigationAction)
return navigation
}
}
// MARK: - WKNavigationDelegate
extension DistributedNavigationDelegate: WKNavigationDelegate {
// MARK: Policy making
@MainActor
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
public func webView(_ webView: WKWebView, decidePolicyFor wkNavigationAction: WKNavigationAction, preferences wkPreferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
// new navigation or an ongoing navigation (for a server-redirect)?
let navigation = navigation(for: wkNavigationAction, in: webView)
// extract WKNavigationAction mapped to NavigationAction from the Navigation or make new for non-main-frame Navigation Actions
let navigationAction = navigation?.navigationAction
?? NavigationAction(webView: webView, navigationAction: wkNavigationAction, currentHistoryItemIdentity: currentHistoryItemIdentity, redirectHistory: nil, mainFrameNavigation: startedNavigation)
// associate NavigationAction with WKNavigationAction object
wkNavigationAction.navigationAction = navigationAction
// only for MainFrame navigations: get currently ongoing (started) MainFrame Navigation
// or Navigation object associated with the NavigationAction (weak)
// it will be different from the Navigation we got above for same-document navigations
let mainFrameNavigation = withExtendedLifetime(navigation) {
navigationAction.isForMainFrame ? navigationAction.mainFrameNavigation : nil
}
// ensure the NavigationAction is added to the Navigation
if let mainFrameNavigation, mainFrameNavigation.navigationActions.isEmpty {
mainFrameNavigation.navigationActionReceived(navigationAction)
}
assert(navigationAction.mainFrameNavigation != nil || !navigationAction.isForMainFrame)
os_log("decidePolicyFor: %s %s", log: log, type: .default, navigationAction.debugDescription, wkNavigationAction.mainFrameNavigation?.debugDescription ?? "")
// initial `about:` scheme navigation doesn‘t wait for decision
if (navigationAction.url.scheme.map(URL.NavigationalScheme.init) == .about
&& (webView.backForwardList.currentItem == nil || navigationAction.navigationType == .sessionRestoration))
// same-document navigations do the same
|| wkNavigationAction.isSameDocumentNavigation && navigationAction.navigationType != .redirect(.server) {
// allow them right away
decisionHandler(.allow, wkPreferences)
if let mainFrameNavigation, !mainFrameNavigation.isCurrent {
self.willStart(mainFrameNavigation)
}
return
}
var preferences = NavigationPreferences(userAgent: webView.customUserAgent, preferences: wkPreferences)
// keep WKNavigationAction alive until the decision is made but not any longer!
var wkNavigationAction: WKNavigationAction! = wkNavigationAction
// pass async decision making to Navigation.navigationResponders (or the delegate navigationResponders for non-main-frame navigations)
let task = makeAsyncDecision(for: navigationAction, boundToLifetimeOf: webView, with: mainFrameNavigation?.navigationResponders ?? responders) { @MainActor responder in
dispatchPrecondition(condition: .onQueue(.main))
// get to next responder until we get non-nil (.next == nil) decision
guard let decision = await responder.decidePolicy(for: navigationAction, preferences: &preferences) else { return .next }
os_log("%s: %s decision: %s", log: self.log, type: .default, navigationAction.debugDescription, "\(type(of: responder))", decision.debugDescription)
// pass non-nil decision to `completion:`
return decision
} completion: { @MainActor [self, weak webView] (decision: NavigationActionPolicy?) in
dispatchPrecondition(condition: .onQueue(.main))
guard let webView else {
decisionHandler(.cancel, wkPreferences)
return
}
switch decision {
case .allow, .none:
if let userAgent = preferences.userAgent {
webView.customUserAgent = userAgent
}
decisionHandler(.allow, preferences.applying(to: wkPreferences))
if let mainFrameNavigation, !mainFrameNavigation.isCurrent {
// another navigation is starting
self.startedNavigation?.didResignCurrent()
self.willStart(mainFrameNavigation)
}
case .cancel:
decisionHandler(.cancel, wkPreferences)
if mainFrameNavigation?.isCurrent != true {
self.didCancelNavigationAction(navigationAction, withRedirectNavigations: nil)
}
case .redirect(_, let redirect):
assert(navigationAction.isForMainFrame)
decisionHandler(.cancel, wkPreferences)
var expectedNavigations = [ExpectedNavigation]()
// run the `redirect` closure with a Navigator wrapper collecting all the ExpectedNavigations produced
withUnsafeMutablePointer(to: &expectedNavigations) { expectedNavigationsPtr in
let navigator = webView.navigator(distributedNavigationDelegate: self, redirectedNavigation: mainFrameNavigation, expectedNavigations: expectedNavigationsPtr)
redirect(navigator)
}
// ignore already started Navigations (they will receive didFail)
if mainFrameNavigation?.isCurrent != true {
didCancelNavigationAction(navigationAction, withRedirectNavigations: expectedNavigations)
}
case .download:
self.willStartDownload(with: navigationAction, in: webView)
decisionHandler(.downloadPolicy, wkPreferences)
}
// don‘t release the original WKNavigationAction until the end
withExtendedLifetime(wkNavigationAction) {}
} /* Task */ cancellation: {
dispatchPrecondition(condition: .onQueue(.main))
os_log("Task cancelled for %s", log: self.log, type: .default, navigationAction.debugDescription)
decisionHandler(.cancel, wkPreferences)
// in case decision making is hung release WKNavigationAction just after cancellation
// to release WKProcessPool and everything bound to it including UserContentController
withExtendedLifetime(wkNavigationAction) {}
wkNavigationAction = nil
}
if navigationAction.isForMainFrame {
// cancel previous `decidePolicyForNavigationAction` async operations when new Navigation begins
self.navigationActionDecisionTask = task
}
}
// swiftlint:enable function_body_length
// swiftlint:enable cyclomatic_complexity
@MainActor
private func willStart(_ navigation: Navigation) {
os_log("willStart %s", log: log, type: .default, navigation.debugDescription)
if case .redirect(.client) = navigation.navigationAction.navigationType {
// notify the original (redirected) Navigation about the redirect NavigationAction received
// this should call the overriden ResponderChain inside `willPerformClientRedirect`
// that in turn notifies the original responders and finishes the Navigation
startedNavigation?.didPerformClientRedirect(with: navigation.navigationAction)
}
navigation.willStart()
for responder in navigation.navigationResponders {
responder.willStart(navigation)
}
navigationExpectedToStart = navigation
}
@MainActor
private func willStartDownload(with navigationAction: NavigationAction, in webView: WKWebView) {
let responders = (navigationAction.isForMainFrame ? navigationAction.mainFrameNavigation?.navigationResponders : nil) ?? responders
for responder in responders {
responder.navigationAction(navigationAction, willBecomeDownloadIn: webView)
}
}
@MainActor
private func didCancelNavigationAction(_ navigationAction: NavigationAction, withRedirectNavigations expectedNavigations: [ExpectedNavigation]?) {
let responders = (navigationAction.isForMainFrame ? navigationAction.mainFrameNavigation?.navigationResponders : nil) ?? responders
for responder in responders {
responder.didCancelNavigationAction(navigationAction, withRedirectNavigations: expectedNavigations)
}
}
// MARK: Pre-Navigation: Auth, Server Redirects
@MainActor
public func webView(_ webView: WKWebView,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// previous navigation may stil be expecting completion at this point
let navigation = navigationExpectedToStart ?? startedNavigation
navigation?.challengeRececived()
os_log("didReceive challenge: %s: %s", log: log, type: .default, navigation?.debugDescription ?? webView.debugDescription, challenge.protectionSpace.description)
makeAsyncDecision(for: navigation?.debugDescription ?? challenge.debugDescription, boundToLifetimeOf: webView, with: navigation?.navigationResponders ?? responders) { @MainActor responder in
dispatchPrecondition(condition: .onQueue(.main))
guard let decision = await responder.didReceive(challenge, for: navigation) else { return .next }
os_log("%s: %s decision: %s", log: self.log, type: .default, String(describing: challenge), "\(type(of: responder))", decision.description)
return decision
} completion: { @MainActor [self] (decision: AuthChallengeDisposition?) in
dispatchPrecondition(condition: .onQueue(.main))
guard let (disposition, credential) = decision?.dispositionAndCredential else {
os_log("%s: performDefaultHandling", log: self.log, type: .default, String(describing: challenge))
completionHandler(.performDefaultHandling, nil)
return
}
completionHandler(disposition, credential)
}
}
@MainActor
public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation wkNavigation: WKNavigation?) {
// previous navigation may stil be expecting completion at this point
guard let navigation = wkNavigation?.navigation ?? navigationExpectedToStart ?? startedNavigation else {
assertionFailure("No navigation is expected to receive server redirect")
return
}
navigation.didReceiveServerRedirect(for: wkNavigation)
os_log("didReceiveServerRedirect %s for: %s", log: log, type: .default, navigation.navigationAction.debugDescription, navigation.debugDescription)
for responder in navigation.navigationResponders {
responder.didReceiveRedirect(navigation.navigationAction, for: navigation)
}
}
// MARK: Navigation
@MainActor
public func webView(_ webView: WKWebView, didStartProvisionalNavigation wkNavigation: WKNavigation?) {
let navigation: Navigation
if let expectedNavigation = navigationExpectedToStart,
wkNavigation != nil
|| expectedNavigation.navigationAction.navigationType == .sessionRestoration
|| expectedNavigation.navigationAction.url.scheme.map(URL.NavigationalScheme.init) == .about {
// regular flow: start .expected navigation
navigation = expectedNavigation
} else if webView.url?.isEmpty == false {
assert(webView.url?.navigationalScheme == .about, "session restoration happening without NavigationAction")
navigation = Navigation(identity: NavigationIdentity(wkNavigation), responders: responders, state: .expected(nil), isCurrent: true)
if let finishedNavigation = wkNavigation?.navigation {
assert(finishedNavigation.state == .finished)
// about: scheme navigation for new window sometimes duplicates didStart/didCommit/didFinish events with the same WKNavigation
let navigationAction = NavigationAction(request: finishedNavigation.request, navigationType: finishedNavigation.navigationAction.navigationType, currentHistoryItemIdentity: nil, redirectHistory: nil, isUserInitiated: false, sourceFrame: finishedNavigation.navigationAction.sourceFrame, targetFrame: finishedNavigation.navigationAction.targetFrame, shouldDownload: false, mainFrameNavigation: navigation)
navigation.navigationActionReceived(navigationAction)
} else {
navigation.navigationActionReceived(.sessionRestoreNavigation(webView: webView, mainFrameNavigation: navigation))
}
navigation.willStart()
} else if let wkNavigation {
navigation = Navigation(identity: NavigationIdentity(wkNavigation), responders: responders, state: .expected(nil), isCurrent: true)
let navigationAction = NavigationAction(request: URLRequest(url: .empty), navigationType: .other, currentHistoryItemIdentity: nil, redirectHistory: nil, isUserInitiated: false, sourceFrame: .mainFrame(for: webView), targetFrame: .mainFrame(for: webView), shouldDownload: false, mainFrameNavigation: navigation)
navigation.navigationActionReceived(navigationAction)
navigation.willStart()
} else {
return
}
navigation.started(wkNavigation)
self.startedNavigation = navigation
self.navigationExpectedToStart = nil
os_log("didStart: %s", log: log, type: .default, navigation.debugDescription)
assert(navigation.navigationAction.navigationType.redirect != .server, "server redirects shouldn‘t call didStartProvisionalNavigation")
for responder in navigation.navigationResponders {
responder.didStart(navigation)
}
}
@MainActor
public func webView(_ webView: WKWebView, decidePolicyFor wkNavigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let navigationResponse = NavigationResponse(navigationResponse: wkNavigationResponse, mainFrameNavigation: startedNavigation)
wkNavigationResponse.navigationResponse = navigationResponse
if wkNavigationResponse.isForMainFrame {
assert(startedNavigation != nil)
startedNavigation?.receivedResponse(navigationResponse)
}
os_log("decidePolicyFor: %s", log: log, type: .default, navigationResponse.debugDescription)
let responders = (navigationResponse.isForMainFrame ? startedNavigation?.navigationResponders : nil) ?? responders
makeAsyncDecision(for: navigationResponse.debugDescription, boundToLifetimeOf: webView, with: responders) { @MainActor responder in
dispatchPrecondition(condition: .onQueue(.main))
guard let decision = await responder.decidePolicy(for: navigationResponse) else { return .next }
os_log("%s: %s decision: %s", log: self.log, type: .default, navigationResponse.debugDescription, "\(type(of: responder))", "\(decision)")
return decision
} completion: { @MainActor [weak self, weak webView] (decision: NavigationResponsePolicy?) in
dispatchPrecondition(condition: .onQueue(.main))
guard let webView else {
decisionHandler(.cancel)
return
}
switch decision {
case .allow, .none:
decisionHandler(.allow)
case .cancel:
decisionHandler(.cancel)
case .download:
self?.willStartDownload(with: navigationResponse, in: webView)
decisionHandler(.downloadPolicy)
}
}
}
// MARK: Client Redirect
#if WILLPERFORMCLIENTREDIRECT_ENABLED
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
@MainActor
@objc(_webView:willPerformClientRedirectToURL:delay:)
public func webView(_ webView: WKWebView, willPerformClientRedirectTo url: URL, delay: TimeInterval) {
for responder in responders {
responder.webViewWillPerformClientRedirect(to: url, withDelay: delay)
}
// willPerformClientRedirect happens whenever WebView is navigated via JS or Refresh header
// we only consider this a "client redirect" when there‘s an ongoing Navigation
guard let redirectedNavigation = startedNavigation,
redirectedNavigation.state.isResponseReceived,
// don‘t handle same-document navigations
!(url.absoluteString.hashedSuffix != nil && redirectedNavigation.url.absoluteString.droppingHashedSuffix() == url.absoluteString.droppingHashedSuffix())
else { return }
os_log("willPerformClientRedirect to: %s, current: %s", log: log, type: .default, url.absoluteString, redirectedNavigation.debugDescription)
// keep the original Navigation non-finished until the redirect NavigationAction is received
let originalResponders = redirectedNavigation.navigationResponders
// notify original Navigation responders after the redirect NavigationAction is received
var sendDidFinishToResponders: ((Navigation) -> Void)?
// override the original Navigation ResponderChain to postpone didFinish event
// otherwise the `startedNavigation` would be set to nil and won‘t be related to new Navigation
var delayedFinishItem: DispatchWorkItem?
var navigationError: WKError?
redirectedNavigation.overrideResponders(redirected: { navigationAction, navigation in
// called from `decidePolicyForNavigationAction`: `startedNavigation.didPerformClientRedirect(with: navigationAction)`
guard !navigation.isCompleted else { return }
delayedFinishItem?.cancel()
// send `didReceiveRedirect` to the original Navigation ResponderChain
for responder in originalResponders {
responder.didReceiveRedirect(navigationAction, for: navigation)
}
guard let sendDidFinish = sendDidFinishToResponders else { return }
// set Navigation state to `finished`
navigation.didSendDidPerformClientRedirectToResponders(with: navigationError)
// send `navigationDidFinish` to the original Navigation ResponderChain (if `navigationDidFinish` already received)
sendDidFinish(navigation)
sendDidFinishToResponders = nil
}, navigationDidFinish: { navigation in
let sendDidFinish = { (navigation: Navigation) in
if !navigation.isCompleted {
navigation.didFinish()
}
for responder in originalResponders {
responder.navigationDidFinish(navigation)
}
}
guard !navigation.isCompleted else {
// in case the navigationDidFinish is received after the `redirected` override already handled, send it now
sendDidFinish(navigation)
return
}
sendDidFinishToResponders = sendDidFinish
// navigationDidFinish is expected to happen before receiving the redirect NavigationAction
// here we delay it to connect current navigation with the new one
delayedFinishItem = DispatchWorkItem {
sendDidFinishToResponders?(navigation)
sendDidFinishToResponders = nil
}
// normally the DispatchWorkItem would never be executed
// just in case anything goes wrong we would still send the didFinish after some delay
DispatchQueue.main.asyncAfter(deadline: .now() + delay + 0.5, execute: delayedFinishItem!)
}, navigationDidFail: { navigation, error in
// normally we should receive "navigationDidFinish", but handling didFail the same way
let sendDidFinish = { (navigation: Navigation) in
if !navigation.isCompleted {
navigation.didFail(with: error)
}
for responder in originalResponders {
responder.navigation(navigation, didFailWith: error)
}
}
guard !navigation.isCompleted else {
sendDidFinish(navigation)
return
}
sendDidFinishToResponders = sendDidFinish
navigationError = error
delayedFinishItem = DispatchWorkItem {
sendDidFinishToResponders?(navigation)
sendDidFinishToResponders = nil
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay + 0.5, execute: delayedFinishItem!)
})
// set Navigation state to .redirected and expect the redirect NavigationAction
redirectedNavigation.willPerformClientRedirect(to: url, delay: delay)
}
// swiftlint:enable function_body_length
// swiftlint:enable cyclomatic_complexity
@MainActor
@objc(_webViewDidCancelClientRedirect:)
public func webViewDidCancelClientRedirect(_ webView: WKWebView) {
os_log("webViewDidCancelClientRedirect", log: log, type: .default)
for responder in responders {
responder.webViewDidCancelClientRedirect(currentNavigation: startedNavigation)
}
if case .willPerformClientRedirect = startedNavigation?.state {
startedNavigation?.didCancelClientRedirect()
}
}
#else
@nonobjc public func webView(_: WKWebView, willPerformClientRedirectTo _: URL, delay: TimeInterval) {}
#endif
// MARK: Completion
@MainActor
public func webView(_ webView: WKWebView, didFinish wkNavigation: WKNavigation?) {
let navigation = wkNavigation?.navigation ?? startedNavigation
guard let navigation,
navigation.identity == wkNavigation.map(NavigationIdentity.init) || wkNavigation == nil
else {
os_log("dropping didFinishNavigation: %s, as another navigation is active: %s", log: log, type: .default, wkNavigation?.description ?? "<nil>", navigation?.debugDescription ?? "<nil>")
return
}
#if PRIVATE_NAVIGATION_DID_FINISH_CALLBACKS_ENABLED
updateCurrentHistoryItemIdentity(webView.backForwardList.currentItem)
#endif
navigation.didFinish(wkNavigation)
os_log("didFinish: %s", log: log, type: .default, navigation.debugDescription)
for responder in navigation.navigationResponders {
responder.navigationDidFinish(navigation)
}
if self.startedNavigation === navigation {
if case .willPerformClientRedirect = navigation.state {
// expecting didPerformClientRedirect
return
}
self.startedNavigation = nil
}
}
@MainActor
public func webView(_ webView: WKWebView, didFail wkNavigation: WKNavigation?, withError error: Error) {
self.webView(webView, didFail: wkNavigation, isProvisional: false, with: error)
}
@MainActor
public func webView(_ webView: WKWebView, didFailProvisionalNavigation wkNavigation: WKNavigation?, withError error: Error) {
self.webView(webView, didFail: wkNavigation, isProvisional: true, with: error)
}
@MainActor
private func webView(_ webView: WKWebView, didFail wkNavigation: WKNavigation?, isProvisional: Bool, with error: Error) {
let error = error as? WKError ?? WKError(_nsError: error as NSError)
let navigation = wkNavigation?.navigation ?? startedNavigation
guard let navigation, navigation.identity == wkNavigation.map(NavigationIdentity.init) || wkNavigation == nil else {
os_log("dropping didFail%sNavigation: %s with: %s, as another navigation is active: %s", log: log, type: .default, isProvisional ? "Provisional" : "", wkNavigation?.description ?? "<nil>", error.errorDescription ?? error.localizedDescription, navigation?.debugDescription ?? "<nil>")
return
}
#if PRIVATE_NAVIGATION_DID_FINISH_CALLBACKS_ENABLED
updateCurrentHistoryItemIdentity(webView.backForwardList.currentItem)
#endif
if navigation.isCurrent && !isProvisional {
navigation.didResignCurrent()
}
navigation.didFail(wkNavigation, with: error)
os_log("didFail %s: %s", log: log, type: .default, navigation.debugDescription, error.errorDescription ?? error.localizedDescription)
for responder in navigation.navigationResponders {
responder.navigation(navigation, didFailWith: error)
}
if self.startedNavigation === navigation {
if case .willPerformClientRedirect = navigation.state {
// expecting didPerformClientRedirect
return
}
self.startedNavigation = nil
}
}
#if PRIVATE_NAVIGATION_DID_FINISH_CALLBACKS_ENABLED
@MainActor
@objc(_webView:navigation:didSameDocumentNavigation:)
public func webView(_ webView: WKWebView, wkNavigation: WKNavigation?, didSameDocumentNavigation navigationType: Int) {
os_log("didSameDocumentNavigation %s: %d", log: log, type: .default, wkNavigation.debugDescription, navigationType)
// currentHistoryItemIdentity should only change for completed navigation, not while in progress
let navigationType = WKSameDocumentNavigationType(rawValue: navigationType)
if case .anchorNavigation = navigationType {
updateCurrentHistoryItemIdentity(webView.backForwardList.currentItem)
}
for responder in responders {
responder.navigation(wkNavigation?.navigation, didSameDocumentNavigationOf: navigationType)
}
}
@MainActor
@objc(_webView:didFinishLoadWithRequest:inFrame:)
public func webView(_ webView: WKWebView, didFinishLoadWith request: URLRequest, in frame: WKFrameInfo) {
updateCurrentHistoryItemIdentity(webView.backForwardList.currentItem)
for responder in responders {
responder.didFinishLoad(with: request, in: frame)
}
}
@MainActor
@objc(_webView:didFailProvisionalLoadWithRequest:inFrame:withError:)
public func webView(_ webView: WKWebView, didFailProvisionalLoadWith request: URLRequest, in frame: WKFrameInfo, with error: Error) {
updateCurrentHistoryItemIdentity(webView.backForwardList.currentItem)
for responder in responders {
responder.didFailProvisionalLoad(with: request, in: frame, with: error)
}
}
#endif
// MARK: Downloads
@MainActor
private func willStartDownload(with navigationResponse: NavigationResponse, in webView: WKWebView) {
let responders = (navigationResponse.isForMainFrame ? navigationResponse.mainFrameNavigation?.navigationResponders : nil) ?? responders
for responder in responders {
responder.navigationResponse(navigationResponse, willBecomeDownloadIn: webView)
}
}
@MainActor
public func webView(_ webView: WKWebView, didCommit wkNavigation: WKNavigation?) {
guard let navigation = wkNavigation?.navigation ?? startedNavigation else {
assert(wkNavigation == nil, "Unexpected didCommitNavigation without preceding didStart")
return
}
#if PRIVATE_NAVIGATION_DID_FINISH_CALLBACKS_ENABLED
updateCurrentHistoryItemIdentity(webView.backForwardList.currentItem)
#endif
navigation.committed(wkNavigation)
os_log("didCommit: %s", log: log, type: .default, navigation.debugDescription)
for responder in navigation.navigationResponders {
responder.didCommit(navigation)
}
}
@MainActor
@available(macOS 11.3, iOS 14.5, *) // objc does‘t care about availability
@objc(webView:navigationAction:didBecomeDownload:)
public func webView(_ webView: WKWebView, navigationAction wkNavigationAction: WKNavigationAction, didBecome download: WKDownload) {
let navigationAction = wkNavigationAction.navigationAction ?? {
assertionFailure("WKNavigationAction has no associated NavigationAction")
return NavigationAction(webView: webView, navigationAction: wkNavigationAction, currentHistoryItemIdentity: currentHistoryItemIdentity, redirectHistory: nil, mainFrameNavigation: startedNavigation)
}()
os_log("navigationActionDidBecomeDownload: %s", log: log, type: .default, navigationAction.debugDescription)
let responders = (navigationAction.isForMainFrame ? navigationAction.mainFrameNavigation?.navigationResponders : nil) ?? responders
for responder in responders {
responder.navigationAction(navigationAction, didBecome: download)
}
if navigationAction.isForMainFrame {
navigationAction.mainFrameNavigation?.didFail(with: WKError(.frameLoadInterruptedByPolicyChange))
}
if navigationAction.isForMainFrame,
let navigation = navigationAction.mainFrameNavigation {
navigation.didFail(with: WKError(.frameLoadInterruptedByPolicyChange))
if startedNavigation === navigation {
self.startedNavigation = nil
}
}
}
@MainActor
@available(macOS 11.3, iOS 14.5, *) // objc does‘t care about availability
@objc(webView:navigationResponse:didBecomeDownload:)
public func webView(_ webView: WKWebView, navigationResponse wkNavigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
let navigationResponse = wkNavigationResponse.navigationResponse ?? {
assertionFailure("WKNavigationResponse has no associated NavigationResponse")
return NavigationResponse(navigationResponse: wkNavigationResponse, mainFrameNavigation: startedNavigation)
}()
os_log("navigationResponseDidBecomeDownload: %s", log: log, type: .default, navigationResponse.debugDescription)
let responders = (navigationResponse.isForMainFrame ? navigationResponse.mainFrameNavigation?.navigationResponders : nil) ?? responders
for responder in responders {
responder.navigationResponse(navigationResponse, didBecome: download)
}
}
// MARK: Termination
@MainActor
public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
self.webView(webView, processDidTerminateWith: nil)
}
#if TERMINATE_WITH_REASON_ENABLED
@MainActor
@objc(_webView:webContentProcessDidTerminateWithReason:)
public func webView(_ webView: WKWebView, webContentProcessDidTerminateWith reason: Int) {
self.webView(webView, processDidTerminateWith: WKProcessTerminationReason(rawValue: reason))
}
#endif
@MainActor
private func webView(_ webView: WKWebView, processDidTerminateWith reason: WKProcessTerminationReason?) {
os_log("%s webContentProcessDidTerminateWithReason: %d", log: log, type: .default, webView.debugDescription, reason?.rawValue ?? -1)
for responder in responders {
responder.webContentProcessDidTerminate(with: reason ?? .init(rawValue: Int.max))
}
if startedNavigation != nil {
var userInfo = [String: Any]()
if let reason {
userInfo[WKProcessTerminationReason.userInfoKey] = reason
}
let error = WKError(WKError.Code.webContentProcessTerminated, userInfo: userInfo)
self.webView(webView, didFail: nil, isProvisional: true, with: error)
self.startedNavigation = nil
}
self.navigationExpectedToStart = nil
}
}
// MARK: - Forwarding
extension DistributedNavigationDelegate {
/// Here Responders can be registered as handlers for custom WKNavigationDelegate methods not implemented in DistributedNavigationDelegate
/// !!! BE CAREFUL:
/// If this method is used to register one of the exclusive delegate methods of higher priority than already present in DistributedNavigationDelegate
/// (such as one of the decidePolicyForNavigationAction (sync/async/with preferences) methods or a higher priority private API method)
/// this will lead to the designated DistributedNavigationDelegate method not called at all.
/// !!! Only one responder can be registered per custom method handler
public func registerCustomDelegateMethodHandler(_ handler: ResponderRefMaker, forSelectorNamed selectorStr: String) {
dispatchPrecondition(condition: .onQueue(.main))
let selector = NSSelectorFromString(selectorStr)
assert(customDelegateMethodHandlers[selector] == nil)
assert((handler.ref.responder as? NSObject)!.responds(to: selector))
customDelegateMethodHandlers[selector] = handler.ref
}
public func registerCustomDelegateMethodHandler(_ handler: ResponderRefMaker, forSelectorsNamed selectors: [String]) {
for selector in selectors {
registerCustomDelegateMethodHandler(handler, forSelectorNamed: selector)
}
}
public override func responds(to selector: Selector!) -> Bool {
if !super.responds(to: selector) {
return customDelegateMethodHandlers[selector] != nil
}
return true
}
public override func forwardingTarget(for selector: Selector!) -> Any? {
return customDelegateMethodHandlers[selector]?.responder
}
}