This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 443
/
BrowserViewController.swift
3360 lines (2871 loc) · 125 KB
/
BrowserViewController.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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import Data
import BraveShared
import BraveCore
import CoreData
import StoreKit
import BraveUI
import NetworkExtension
import FeedKit
import SwiftUI
import class Combine.AnyCancellable
import BraveWallet
import BraveVPN
import BraveNews
import Preferences
import os.log
#if canImport(BraveTalk)
import BraveTalk
#endif
import Favicon
import Onboarding
import Growth
import BraveShields
import CertificateUtilities
import ScreenTime
private let KVOs: [KVOConstants] = [
.estimatedProgress,
.loading,
.canGoBack,
.canGoForward,
.URL,
.title,
.hasOnlySecureContent,
.serverTrust,
._sampledPageTopColor
]
public class BrowserViewController: UIViewController {
let webViewContainer = UIView()
private(set) lazy var screenshotHelper = ScreenshotHelper(tabManager: tabManager)
private(set) lazy var topToolbar: TopToolbarView = {
// Setup the URL bar, wrapped in a view to get transparency effect
let topToolbar = TopToolbarView(voiceSearchSupported: speechRecognizer.isVoiceSearchAvailable, privateBrowsingManager: privateBrowsingManager)
topToolbar.translatesAutoresizingMaskIntoConstraints = false
topToolbar.delegate = self
topToolbar.tabToolbarDelegate = self
let toolBarInteraction = UIContextMenuInteraction(delegate: self)
topToolbar.locationView.addInteraction(toolBarInteraction)
return topToolbar
}()
private(set) lazy var tabsBar: TabsBarViewController = {
let tabsBar = TabsBarViewController(tabManager: tabManager)
tabsBar.delegate = self
return tabsBar
}()
// These views wrap the top and bottom toolbars to provide background effects on them
private(set) lazy var header = HeaderContainerView(privateBrowsingManager: privateBrowsingManager)
private let headerHeightLayoutGuide = UILayoutGuide()
let footer: UIView = {
let footer = UIView()
footer.translatesAutoresizingMaskIntoConstraints = false
return footer
}()
private let topTouchArea: UIButton = {
let topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
return topTouchArea
}()
private let bottomTouchArea: UIButton = {
let bottomTouchArea = UIButton()
bottomTouchArea.isAccessibilityElement = false
return bottomTouchArea
}()
/// These constraints allow to show/hide tabs bar
private var webViewContainerTopOffset: Constraint?
/// Backdrop used for displaying greyed background for private tabs
private let webViewContainerBackdrop: UIView = {
let webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = .braveBackground
webViewContainerBackdrop.alpha = 0
return webViewContainerBackdrop
}()
var readerModeBar: ReaderModeBarView?
var readerModeCache: ReaderModeCache
private(set) lazy var statusBarOverlay: UIView = {
// Temporary work around for covering the non-clipped web view content
let statusBarOverlay = UIView()
statusBarOverlay.backgroundColor = privateBrowsingManager.browserColors.chromeBackground
return statusBarOverlay
}()
private(set) var toolbar: BottomToolbarView?
var searchLoader: SearchLoader?
var searchController: SearchViewController?
var favoritesController: FavoritesViewController?
/// All content that appears above the footer should be added to this view. (Find In Page/SnackBars)
let alertStackView: UIStackView = {
let alertStackView = UIStackView()
alertStackView.axis = .vertical
alertStackView.alignment = .center
return alertStackView
}()
var findInPageBar: FindInPageBar?
var pageZoomBar: UIHostingController<PageZoomView>?
private var pageZoomListener: NSObjectProtocol?
private var openTabsModelStateListener: SendTabToSelfModelStateListener?
private var syncServiceStateListener: AnyObject?
let collapsedURLBarView = CollapsedURLBarView()
// Single data source used for all favorites vcs
public let backgroundDataSource: NTPDataSource
let feedDataSource: FeedDataSource
private var postSetupTasks: [() -> Void] = []
private var setupTasksCompleted: Bool = false
private var privateModeCancellable: AnyCancellable?
private var appReviewCancelable: AnyCancellable?
var onPendingRequestUpdatedCancellable: AnyCancellable?
/// Voice Search
var voiceSearchViewController: PopupViewController<VoiceSearchInputView>?
var voiceSearchCancelable: AnyCancellable?
let speechRecognizer = SpeechRecognizer()
/// Custom Search Engine
var openSearchEngine: OpenSearchReference?
lazy var customSearchEngineButton = OpenSearchEngineButton(hidesWhenDisabled: false).then {
$0.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside)
$0.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton"
$0.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
$0.setContentHuggingPriority(.defaultHigh, for: .horizontal)
}
var customSearchBarButtonItemGroup: UIBarButtonItemGroup?
// popover rotation handling
var displayedPopoverController: UIViewController?
var updateDisplayedPopoverProperties: (() -> Void)?
public let windowId: UUID
let profile: Profile
let braveCore: BraveCoreMain
let tabManager: TabManager
let migration: Migration?
let bookmarkManager: BookmarkManager
public let privateBrowsingManager: PrivateBrowsingManager
/// Whether last session was a crash or not
private let crashedLastSession: Bool
// A view to place behind the bottom bar down to the toolbar during keyboard animations to avoid
// the odd look for the URL bar floating
private let bottomBarKeyboardBackground = UIView().then {
$0.isUserInteractionEnabled = false
}
var toolbarVisibilityViewModel = ToolbarVisibilityViewModel(estimatedTransitionDistance: 44)
private var toolbarLayoutGuide = UILayoutGuide().then {
$0.identifier = "toolbar-visibility-layout-guide"
}
private var toolbarTopConstraint: Constraint?
private var toolbarBottomConstraint: Constraint?
var toolbarVisibilityCancellable: AnyCancellable?
var keyboardState: KeyboardState?
var pendingToast: Toast? // A toast that might be waiting for BVC to appear before displaying
var downloadToast: DownloadToast? // A toast that is showing the combined download progress
var addToPlayListActivityItem: (enabled: Bool, item: PlaylistInfo?)? // A boolean to determine If AddToListActivity should be added
var openInPlaylistActivityItem: (enabled: Bool, item: PlaylistInfo?)? // A boolean to determine if OpenInPlaylistActivity should be shown
var typedNavigation = [URL: VisitType]()
var navigationToolbar: ToolbarProtocol {
return toolbar ?? topToolbar
}
// Keep track of allowed `URLRequest`s from `webView(_:decidePolicyFor:decisionHandler:)` so
// that we can obtain the originating `URLRequest` when a `URLResponse` is received. This will
// allow us to re-trigger the `URLRequest` if the user requests a file to be downloaded.
var pendingRequests = [String: URLRequest]()
// This is set when the user taps "Download Link" from the context menu. We then force a
// download of the next request through the `WKNavigationDelegate` that matches this web view.
weak var pendingDownloadWebView: WKWebView?
let downloadQueue = DownloadQueue()
private var cancellables: Set<AnyCancellable> = []
let rewards: BraveRewards
var rewardsObserver: RewardsObserver?
var promotionFetchTimer: Timer?
private var notificationsHandler: AdsNotificationHandler?
let notificationsPresenter = BraveNotificationsPresenter()
var publisher: BraveCore.BraveRewards.PublisherInfo?
let vpnProductInfo = VPNProductInfo()
/// Window Protection instance which will be used for controller requires biometric authentication
public var windowProtection: WindowProtection?
// Product Notification Related Properties
/// Boolean which is tracking If a product notification is presented
/// in order to not to try to present another one over existing popover
var benchmarkNotificationPresented = false
/// The string domain will be kept temporarily which is tracking site notification presented
/// in order to not to process site list again and again
var currentBenchmarkWebsite = ""
/// Used to determine when to present benchmark pop-overs
/// Current session ad count is compared with live ad count
/// So user will not be introduced with a pop-over directly
let benchmarkCurrentSessionAdCount = BraveGlobalShieldStats.shared.adblock + BraveGlobalShieldStats.shared.trackingProtection
/// Navigation Helper used for Brave Widgets
private(set) lazy var navigationHelper = BrowserNavigationHelper(self)
/// Boolean tracking if Tab Tray is active on the screen
/// Used to determine If pop-over should be presented
var isTabTrayActive = false
/// Data Source object used to determine blocking stats
var benchmarkBlockingDataSource: BlockingSummaryDataSource?
/// Boolean which is tracking If a full screen callout or onboarding is presented
/// in order to not to try to present another callout over existing one
var isOnboardingOrFullScreenCalloutPresented = false
private(set) var widgetBookmarksFRC: NSFetchedResultsController<Favorite>?
var widgetFaviconFetchers: [Task<Favicon, Error>] = []
let deviceCheckClient: DeviceCheckClient?
#if canImport(BraveTalk)
// Brave Talk native implementations
let braveTalkJitsiCoordinator = BraveTalkJitsiCoordinator()
#endif
/// The currently open WalletStore
weak var walletStore: WalletStore?
var lastEnteredURLVisitType: VisitType = .unknown
var processAddressBarTask: Task<(), Never>?
var topToolbarDidPressReloadTask: Task<(), Never>?
public init(
windowId: UUID,
profile: Profile,
diskImageStore: DiskImageStore?,
braveCore: BraveCoreMain,
rewards: BraveRewards,
migration: Migration?,
crashedLastSession: Bool,
newsFeedDataSource: FeedDataSource,
privateBrowsingManager: PrivateBrowsingManager
) {
self.windowId = windowId
self.profile = profile
self.braveCore = braveCore
self.bookmarkManager = BookmarkManager(bookmarksAPI: braveCore.bookmarksAPI)
self.rewards = rewards
self.migration = migration
self.crashedLastSession = crashedLastSession
self.privateBrowsingManager = privateBrowsingManager
self.feedDataSource = newsFeedDataSource
feedDataSource.historyAPI = braveCore.historyAPI
backgroundDataSource = .init(service: braveCore.backgroundImagesService,
privateBrowsingManager: privateBrowsingManager)
// Initialize TabManager
self.tabManager = TabManager(
windowId: windowId,
prefs: profile.prefs,
rewards: rewards,
tabGeneratorAPI: braveCore.tabGeneratorAPI,
privateBrowsingManager: privateBrowsingManager
)
// Add Regular tabs to Sync Chain
if Preferences.Chromium.syncOpenTabsEnabled.value {
tabManager.addRegularTabsToSyncChain()
}
// Remove outdated Recently Closed tabs
tabManager.deleteOutdatedRecentlyClosed()
// Setup ReaderMode Cache
self.readerModeCache = ReaderModeScriptHandler.cache(for: tabManager.selectedTab)
if !BraveRewards.isAvailable {
// Disable rewards services in case previous user already enabled
// rewards in previous build
rewards.isEnabled = false
} else {
if rewards.isEnabled && !Preferences.Rewards.rewardsToggledOnce.value {
Preferences.Rewards.rewardsToggledOnce.value = true
}
}
self.deviceCheckClient = DeviceCheckClient(environment: BraveRewards.Configuration.current().environment)
if Locale.current.regionCode == "JP" {
benchmarkBlockingDataSource = BlockingSummaryDataSource()
}
super.init(nibName: nil, bundle: nil)
didInit()
rewards.rewardsServiceDidStart = { [weak self] _ in
self?.setupLedger()
}
rewards.ads.captchaHandler = self
let shouldStartAds = rewards.ads.isEnabled || Preferences.BraveNews.isEnabled.value
if shouldStartAds {
// Only start rewards service automatically if ads is enabled
if rewards.isEnabled {
rewards.startRewardsService(nil)
} else {
rewards.ads.initialize() { _ in }
}
}
self.feedDataSource.getAdsAPI = {
// The ads object gets re-recreated when shutdown, so we need to make sure News fetches it out of
// the BraveRewards container
return rewards.ads
}
// Observer watching tab information is sent by another device
openTabsModelStateListener = braveCore.sendTabAPI.add(
SendTabToSelfStateObserver { [weak self] stateChange in
if case .sendTabToSelfEntriesAddedRemotely(let newEntries) = stateChange {
// Fetching the last URL that has been sent from synced sessions
if let requestedURL = newEntries.last?.url {
self?.presentTabReceivedToast(url: requestedURL)
}
}
})
// Observer watching state change in sync chain
syncServiceStateListener = braveCore.syncAPI.addServiceStateObserver { [weak self] in
guard let self = self else { return }
// Observe Sync State in order to determine if the sync chain is deleted
// from another device - Clean local sync chain
if self.braveCore.syncAPI.shouldLeaveSyncGroup {
self.braveCore.syncAPI.leaveSyncGroup()
}
}
if Preferences.Privacy.screenTimeEnabled.value {
screenTimeViewController = STWebpageController()
}
}
deinit {
// Remove the open tabs model state observer
if let observer = openTabsModelStateListener {
braveCore.sendTabAPI.removeObserver(observer)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
dismissVisibleMenus()
coordinator.animate(
alongsideTransition: { context in
if let popover = self.displayedPopoverController {
self.updateDisplayedPopoverProperties?()
self.present(popover, animated: true, completion: nil)
}
#if canImport(BraveTalk)
self.braveTalkJitsiCoordinator.resetPictureInPictureBounds(.init(size: size))
#endif
},
completion: { _ in
if let tab = self.tabManager.selectedTab {
WindowRenderScriptHandler.executeScript(for: tab)
}
})
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
ScriptFactory.shared.clearCaches()
Task {
await AdBlockStats.shared.didReceiveMemoryWarning()
}
for tab in tabManager.tabsForCurrentMode where tab.id != tabManager.selectedTab?.id {
tab.newTabPageViewController = nil
}
}
private var rewardsEnabledObserveration: NSKeyValueObservation?
fileprivate func didInit() {
updateApplicationShortcuts()
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
UserScriptManager.shared.fetchWalletScripts(from: braveCore.braveWalletAPI)
downloadQueue.delegate = self
// Observe some user preferences
Preferences.Privacy.privateBrowsingOnly.observe(from: self)
Preferences.General.tabBarVisibility.observe(from: self)
Preferences.UserAgent.alwaysRequestDesktopSite.observe(from: self)
Preferences.General.enablePullToRefresh.observe(from: self)
Preferences.General.mediaAutoBackgrounding.observe(from: self)
Preferences.General.youtubeHighQuality.observe(from: self)
Preferences.General.defaultPageZoomLevel.observe(from: self)
Preferences.Shields.allShields.forEach { $0.observe(from: self) }
Preferences.Privacy.blockAllCookies.observe(from: self)
Preferences.Rewards.hideRewardsIcon.observe(from: self)
Preferences.Rewards.rewardsToggledOnce.observe(from: self)
Preferences.Playlist.enablePlaylistMenuBadge.observe(from: self)
Preferences.Playlist.enablePlaylistURLBarButton.observe(from: self)
Preferences.Playlist.syncSharedFoldersAutomatically.observe(from: self)
Preferences.NewTabPage.backgroundSponsoredImages.observe(from: self)
ShieldPreferences.blockAdsAndTrackingLevelRaw.observe(from: self)
Preferences.Privacy.screenTimeEnabled.observe(from: self)
pageZoomListener = NotificationCenter.default.addObserver(forName: PageZoomView.notificationName, object: nil, queue: .main) { [weak self] _ in
self?.tabManager.allTabs.forEach({
guard let url = $0.webView?.url else { return }
let zoomLevel = self?.privateBrowsingManager.isPrivateBrowsing == true ? 1.0 : Domain.getPersistedDomain(for: url)?.zoom_level?.doubleValue ?? Preferences.General.defaultPageZoomLevel.value
$0.webView?.setValue(zoomLevel, forKey: PageZoomView.propertyName)
})
}
rewardsEnabledObserveration = rewards.observe(\.isEnabled, options: [.new]) { [weak self] _, _ in
guard let self = self else { return }
self.updateRewardsButtonState()
self.setupAdsNotificationHandler()
self.recordAdsUsageType()
}
Preferences.Playlist.webMediaSourceCompatibility.observe(from: self)
Preferences.PrivacyReports.captureShieldsData.observe(from: self)
Preferences.PrivacyReports.captureVPNAlerts.observe(from: self)
Preferences.Wallet.defaultEthWallet.observe(from: self)
if rewards.rewardsAPI != nil {
// Ledger was started immediately due to user having ads enabled
setupLedger()
}
Preferences.NewTabPage.attemptToShowClaimRewardsNotification.value = true
backgroundDataSource.initializeFavorites = { sites in
DispatchQueue.main.async {
defer { Preferences.NewTabPage.preloadedFavoritiesInitialized.value = true }
if Preferences.NewTabPage.preloadedFavoritiesInitialized.value
|| Favorite.hasFavorites {
return
}
guard let sites = sites, !sites.isEmpty else {
FavoritesHelper.addDefaultFavorites()
return
}
let customFavorites = sites.compactMap { $0.asFavoriteSite }
Favorite.add(from: customFavorites)
}
}
setupAdsNotificationHandler()
backgroundDataSource.replaceFavoritesIfNeeded = { sites in
if Preferences.NewTabPage.initialFavoritesHaveBeenReplaced.value { return }
guard let sites = sites, !sites.isEmpty else { return }
DispatchQueue.main.async {
let defaultFavorites = PreloadedFavorites.getList()
let currentFavorites = Favorite.allFavorites
if defaultFavorites.count != currentFavorites.count {
return
}
let exactSameFavorites = Favorite.allFavorites
.filter {
guard let urlString = $0.url,
let url = URL(string: urlString),
let title = $0.displayTitle
else {
return false
}
return defaultFavorites.contains(where: { defaultFavorite in
defaultFavorite.url == url && defaultFavorite.title == title
})
}
if currentFavorites.count == exactSameFavorites.count {
let customFavorites = sites.compactMap { $0.asFavoriteSite }
Preferences.NewTabPage.initialFavoritesHaveBeenReplaced.value = true
Favorite.forceOverwriteFavorites(with: customFavorites)
}
}
}
// Setup Widgets FRC
widgetBookmarksFRC = Favorite.frc()
widgetBookmarksFRC?.fetchRequest.fetchLimit = 16
widgetBookmarksFRC?.delegate = self
try? widgetBookmarksFRC?.performFetch()
updateWidgetFavoritesData()
// Eliminate the older usage days
// Used in App Rating criteria
AppReviewManager.shared.processMainCriteria(for: .daysInUse)
// P3A Record
maybeRecordInitialShieldsP3A()
recordVPNUsageP3A(vpnEnabled: BraveVPN.isConnected)
recordAccessibilityDisplayZoomEnabledP3A()
recordAccessibilityDocumentsDirectorySizeP3A()
recordTimeBasedNumberReaderModeUsedP3A(activated: false)
recordGeneralBottomBarLocationP3A()
PlaylistP3A.recordHistogram()
recordAdsUsageType()
// Revised Review Handling
AppReviewManager.shared.handleAppReview(for: .revisedCrossPlatform, using: self)
}
private func setupAdsNotificationHandler() {
notificationsHandler = AdsNotificationHandler(ads: rewards.ads,
presentingController: self,
notificationsPresenter: notificationsPresenter)
notificationsHandler?.canShowNotifications = { [weak self] in
guard let self = self else { return false }
return !self.privateBrowsingManager.isPrivateBrowsing && !self.topToolbar.inOverlayMode
}
notificationsHandler?.actionOccured = { [weak self] ad, action in
guard let self = self, let ad = ad else { return }
if action == .opened {
var url = URL(string: ad.targetURL)
if url == nil,
let percentEncodedURLString =
ad.targetURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
// Try to percent-encode the string and try that
url = URL(string: percentEncodedURLString)
}
guard let targetURL = url else {
assertionFailure("Invalid target URL for creative instance id: \(ad.creativeInstanceID)")
return
}
let request = URLRequest(url: targetURL)
self.tabManager.addTabAndSelect(request, isPrivate: self.privateBrowsingManager.isPrivateBrowsing)
}
}
}
func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular
}
private func updateUsingBottomBar(using traitCollection: UITraitCollection) {
isUsingBottomBar = Preferences.General.isUsingBottomBar.value &&
traitCollection.horizontalSizeClass == .compact &&
traitCollection.verticalSizeClass == .regular &&
traitCollection.userInterfaceIdiom == .phone
// Reinserts the fav controller whos parent is based on bottom bar
if let favoritesController {
insertFavoritesControllerView(favoritesController: favoritesController)
}
}
public override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
topTouchArea.isEnabled = view.safeAreaInsets.top > 0
statusBarOverlay.isHidden = view.safeAreaInsets.top.isZero
}
fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
topToolbar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.tabToolbarDelegate = nil
toolbar = nil
bottomTouchArea.isEnabled = showToolbar
if showToolbar {
toolbar = BottomToolbarView(privateBrowsingManager: privateBrowsingManager)
toolbar?.setSearchButtonState(url: tabManager.selectedTab?.url)
footer.addSubview(toolbar!)
toolbar?.tabToolbarDelegate = self
toolbar?.menuButton.setBadges(Array(topToolbar.menuButton.badges.keys))
}
updateToolbarUsingTabManager(tabManager)
updateUsingBottomBar(using: newCollection)
view.setNeedsUpdateConstraints()
if let tab = tabManager.selectedTab,
let webView = tab.webView {
updateURLBar()
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
topToolbar.locationView.loading = tab.loading
}
toolbarVisibilityViewModel.toolbarState = .expanded
updateTabsBarVisibility()
}
private func updateToolbarSecureContentState(_ secureContentState: TabSecureContentState) {
topToolbar.secureContentState = secureContentState
collapsedURLBarView.secureContentState = secureContentState
}
func updateToolbarCurrentURL(_ currentURL: URL?) {
topToolbar.currentURL = currentURL
collapsedURLBarView.currentURL = currentURL
updateScreenTimeUrl(currentURL)
}
override public func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
// During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to
// set things up. Make sure to only update the toolbar state if the view is ready for it.
if isViewLoaded {
updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator)
}
displayedPopoverController?.dismiss(animated: true, completion: nil)
coordinator.animate(
alongsideTransition: { context in
if self.isViewLoaded {
self.updateStatusBarOverlayColor()
self.bottomBarKeyboardBackground.backgroundColor = self.topToolbar.backgroundColor
self.setNeedsStatusBarAppearanceUpdate()
}
},
completion: { _ in
if let tab = self.tabManager.selectedTab {
WindowRenderScriptHandler.executeScript(for: tab)
}
})
}
func dismissVisibleMenus() {
displayedPopoverController?.dismiss(animated: true)
}
@objc func sceneDidEnterBackgroundNotification(_ notification: NSNotification) {
guard let scene = notification.object as? UIScene, scene == currentScene else {
return
}
displayedPopoverController?.dismiss(animated: false) {
self.updateDisplayedPopoverProperties = nil
self.displayedPopoverController = nil
}
}
@objc func appWillTerminateNotification() {
tabManager.saveAllTabs()
tabManager.removePrivateWindows()
}
@objc private func tappedCollapsedURLBar() {
if keyboardState != nil && isUsingBottomBar && !topToolbar.inOverlayMode {
view.endEditing(true)
} else {
tappedTopArea()
}
}
@objc func tappedTopArea() {
toolbarVisibilityViewModel.toolbarState = .expanded
}
@objc func sceneWillResignActiveNotification(_ notification: NSNotification) {
guard let scene = notification.object as? UIScene, scene == currentScene else {
return
}
tabManager.saveAllTabs()
// Dismiss any popovers that might be visible
displayedPopoverController?.dismiss(animated: false) {
self.updateDisplayedPopoverProperties = nil
self.displayedPopoverController = nil
}
// If we are displaying a private tab, hide any elements in the tab that we wouldn't want shown
// when the app is in the home switcher
if let tab = tabManager.selectedTab, tab.isPrivate {
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
activeNewTabPageViewController?.view.alpha = 0
favoritesController?.view.alpha = 0
searchController?.view.alpha = 0
header.contentView.alpha = 0
presentedViewController?.popoverPresentationController?.containerView?.alpha = 0
presentedViewController?.view.alpha = 0
}
// Stop Voice Search and dismiss controller
stopVoiceSearch()
}
@objc func vpnConfigChanged() {
// Load latest changes to the vpn.
NEVPNManager.shared().loadFromPreferences { _ in }
if case .purchased(let enabled) = BraveVPN.vpnState, enabled {
recordVPNUsageP3A(vpnEnabled: true)
}
}
@objc func sceneDidBecomeActiveNotification(_ notification: NSNotification) {
guard let scene = notification.object as? UIScene, scene == currentScene else {
return
}
guard let tab = tabManager.selectedTab, tab.isPrivate else {
return
}
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(
withDuration: 0.2, delay: 0, options: UIView.AnimationOptions(),
animations: {
self.webViewContainer.alpha = 1
self.header.contentView.alpha = 1
self.activeNewTabPageViewController?.view.alpha = 1
self.favoritesController?.view.alpha = 1
self.searchController?.view.alpha = 1
self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1
self.presentedViewController?.view.alpha = 1
self.view.backgroundColor = .clear
},
completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
}
private(set) var isUsingBottomBar: Bool = false {
didSet {
header.isUsingBottomBar = isUsingBottomBar
collapsedURLBarView.isUsingBottomBar = isUsingBottomBar
searchController?.isUsingBottomBar = isUsingBottomBar
bottomBarKeyboardBackground.isHidden = !isUsingBottomBar
topToolbar.displayTabTraySwipeGestureRecognizer?.isEnabled = isUsingBottomBar
updateTabsBarVisibility()
updateStatusBarOverlayColor()
updateViewConstraints()
}
}
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .braveBackground
// Add layout guides
view.addLayoutGuide(pageOverlayLayoutGuide)
view.addLayoutGuide(headerHeightLayoutGuide)
view.addLayoutGuide(toolbarLayoutGuide)
// Add views
view.addSubview(webViewContainerBackdrop)
view.addSubview(webViewContainer)
header.expandedBarStackView.addArrangedSubview(topToolbar)
header.collapsedBarContainerView.addSubview(collapsedURLBarView)
addChild(tabsBar)
tabsBar.didMove(toParent: self)
view.addSubview(alertStackView)
view.addSubview(bottomTouchArea)
view.addSubview(topTouchArea)
view.addSubview(bottomBarKeyboardBackground)
view.addSubview(footer)
view.addSubview(statusBarOverlay)
view.addSubview(header)
// For now we hide some elements so they are not visible
header.isHidden = true
footer.isHidden = true
// Setup constraints
setupConstraints()
updateToolbarStateForTraitCollection(self.traitCollection)
// Legacy Review Handling
AppReviewManager.shared.handleAppReview(for: .legacy, using: self)
// Adding Screenshot Service Delegate to browser to fetch full screen webview screenshots
currentScene?.screenshotService?.delegate = self
self.setupInteractions()
}
private func setupInteractions() {
// We now show some elements since we're ready to use the app
header.isHidden = false
footer.isHidden = false
NotificationCenter.default.do {
$0.addObserver(
self, selector: #selector(sceneWillResignActiveNotification(_:)),
name: UIScene.willDeactivateNotification, object: nil)
$0.addObserver(
self, selector: #selector(sceneDidBecomeActiveNotification(_:)),
name: UIScene.didActivateNotification, object: nil)
$0.addObserver(
self, selector: #selector(sceneDidEnterBackgroundNotification),
name: UIScene.didEnterBackgroundNotification, object: nil)
$0.addObserver(
self, selector: #selector(appWillTerminateNotification),
name: UIApplication.willTerminateNotification, object: nil)
$0.addObserver(
self, selector: #selector(resetNTPNotification),
name: .adsOrRewardsToggledInSettings, object: nil)
$0.addObserver(
self, selector: #selector(vpnConfigChanged),
name: .NEVPNConfigurationChange, object: nil)
$0.addObserver(
self, selector: #selector(updateShieldNotifications),
name: NSNotification.Name(rawValue: BraveGlobalShieldStats.didUpdateNotification), object: nil)
}
BraveGlobalShieldStats.shared.$adblock
.scan((BraveGlobalShieldStats.shared.adblock, BraveGlobalShieldStats.shared.adblock), { ($0.1, $1) })
.sink { [weak self] (oldValue, newValue) in
let change = newValue - oldValue
if change > 0 {
self?.recordDataSavedP3A(change: change)
}
}
.store(in: &cancellables)
KeyboardHelper.defaultHelper.addDelegate(self)
UNUserNotificationCenter.current().delegate = self
// Add interactions
topTouchArea.addTarget(self, action: #selector(tappedTopArea), for: .touchUpInside)
bottomTouchArea.addTarget(self, action: #selector(tappedTopArea), for: .touchUpInside)
header.collapsedBarContainerView.addTarget(self, action: #selector(tappedCollapsedURLBar), for: .touchUpInside)
updateRewardsButtonState()
// Setup UIDropInteraction to handle dragging and dropping
// links into the view from other apps.
let dropInteraction = UIDropInteraction(delegate: self)
view.addInteraction(dropInteraction)
topToolbar.addInteraction(dropInteraction)
// Adding a small delay before fetching gives more reliability to it,
// epsecially when you are connected to a VPN.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.vpnProductInfo.load()
if let customCredential = Preferences.VPN.skusCredential.value,
let customCredentialDomain = Preferences.VPN.skusCredentialDomain.value,
let vpnCredential = BraveSkusWebHelper.fetchVPNCredential(customCredential, domain: customCredentialDomain) {
BraveVPN.initialize(customCredential: vpnCredential)
} else {
BraveVPN.initialize(customCredential: nil)
}
}
// Schedule Default Browser Local Notification
// If notification is not already scheduled or
// an external URL opened in Brave (which indicates Brave is set as default)
if !Preferences.DefaultBrowserIntro.defaultBrowserNotificationScheduled.value {
scheduleDefaultBrowserNotification()
}
privateModeCancellable = privateBrowsingManager
.$isPrivateBrowsing
.removeDuplicates()
.receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] isPrivateBrowsing in
guard let self = self else { return }
self.updateStatusBarOverlayColor()
self.bottomBarKeyboardBackground.backgroundColor = self.topToolbar.backgroundColor
self.collapsedURLBarView.browserColors = self.privateBrowsingManager.browserColors
})
appReviewCancelable = AppReviewManager.shared
.$isRevisedReviewRequired
.removeDuplicates()
.sink(receiveValue: { [weak self] isRevisedReviewRequired in
guard let self = self else { return }
if isRevisedReviewRequired {
AppReviewManager.shared.isRevisedReviewRequired = false
// Handle App Rating
// User made changes to the Brave News sources (tapped close)
AppReviewManager.shared.handleAppReview(for: .revised, using: self)
}
})
Preferences.General.isUsingBottomBar.objectWillChange
.receive(on: RunLoop.main)
.sink { [weak self] _ in
guard let self = self else { return }
self.updateTabsBarVisibility()
self.updateUsingBottomBar(using: self.traitCollection)
}
.store(in: &cancellables)
syncPlaylistFolders()
checkCrashRestorationOrSetupTabs()
}
public static let defaultBrowserNotificationId = "defaultBrowserNotification"
private func scheduleDefaultBrowserNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.provisional, .alert, .sound, .badge]) { granted, error in
if let error = error {
Logger.module.error("Failed to request notifications permissions: \(error.localizedDescription, privacy: .public)")
return
}
if !granted {
Logger.module.info("Not authorized to schedule a notification")
return
}
center.getPendingNotificationRequests { requests in
if requests.contains(where: { $0.identifier == Self.defaultBrowserNotificationId }) {
// Already has one scheduled no need to schedule again.
return
}
let content = UNMutableNotificationContent().then {
$0.title = Strings.DefaultBrowserCallout.notificationTitle
$0.body = Strings.DefaultBrowserCallout.notificationBody
}
let timeToShow = AppConstants.buildChannel.isPublic ? 2.hours : 2.minutes
let timeTrigger = UNTimeIntervalNotificationTrigger(timeInterval: timeToShow, repeats: false)
let request = UNNotificationRequest(
identifier: Self.defaultBrowserNotificationId,
content: content,
trigger: timeTrigger)
center.add(request) { error in
if let error = error {
Logger.module.error("Failed to add notification: \(error.localizedDescription, privacy: .public)")
return
}
Preferences.DefaultBrowserIntro.defaultBrowserNotificationScheduled.value = true
}
}
}