-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathTabManager.swift
More file actions
1725 lines (1492 loc) · 55.2 KB
/
Copy pathTabManager.swift
File metadata and controls
1725 lines (1492 loc) · 55.2 KB
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 https://mozilla.org/MPL/2.0/.
import BraveCore
import BraveShields
import BraveWallet
import CoreData
import Data
import Favicon
import Foundation
import Growth
import Preferences
import Shared
import Storage
import Web
import WebKit
import os.log
protocol TabManagerDelegate: AnyObject {
func tabManager(
_ tabManager: TabManager,
didSelectedTabChange selected: (any TabState)?,
previous: (any TabState)?
)
func tabManager(_ tabManager: TabManager, willAddTab tab: some TabState)
func tabManager(_ tabManager: TabManager, didAddTab tab: some TabState)
func tabManager(_ tabManager: TabManager, willRemoveTab tab: some TabState)
func tabManager(_ tabManager: TabManager, didRemoveTab tab: some TabState)
func tabManagerDidRestoreTabs(_ tabManager: TabManager)
func tabManagerDidAddTabs(_ tabManager: TabManager)
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?)
}
protocol TabManagerStateDelegate: AnyObject {
func tabManagerWillStoreTabs(_ tabs: [any TabState])
}
// We can't use a WeakList here because this is a protocol.
class WeakTabManagerDelegate {
weak var value: TabManagerDelegate?
init(value: TabManagerDelegate) {
self.value = value
}
func get() -> TabManagerDelegate? {
return value
}
}
// TabManager must extend NSObjectProtocol in order to implement WKNavigationDelegate
class TabManager: NSObject {
fileprivate var delegates = [WeakTabManagerDelegate]()
weak var stateDelegate: TabManagerStateDelegate?
/// Internal url to access the new tab page.
static let ntpInteralURL = URL(string: "about://newtab")!
/// When a URL is invalid and can't be restored or loaded, we display about:blank#blocked (same as on Desktop)
static let aboutBlankBlockedURL = URL(string: "about:blank")!
func addDelegate(_ delegate: TabManagerDelegate) {
assert(Thread.isMainThread)
delegates.append(WeakTabManagerDelegate(value: delegate))
}
func removeDelegate(_ delegate: TabManagerDelegate) {
assert(Thread.isMainThread)
for i in 0..<delegates.count {
let del = delegates[i]
if delegate === del.get() || del.get() == nil {
delegates.remove(at: i)
return
}
}
}
private(set) var allTabs = [any TabState]()
private var _selectedIndex = -1
private(set) var isRestoring = false
private(set) var isBulkDeleting = false
var selectedIndex: Int {
return _selectedIndex
}
var normalTabSelectedIndex: Int?
var privateTabSelectedIndex: Int?
var tempTabs: [any TabState]?
private weak var rewards: BraveRewards?
private var braveCore: BraveProfileController?
private let profile: any Profile
private weak var tabGeneratorAPI: BraveTabGeneratorAPI?
private var domainFrc = Domain.frc()
private let syncedTabsQueue = DispatchQueue(label: "synced-tabs-queue")
private var syncTabsTask: DispatchWorkItem?
private var metricsHeartbeat: Timer?
private let historyAPI: BraveHistoryAPI?
public let privateBrowsingManager: PrivateBrowsingManager
private var forgetTasks: [Bool: [String: Task<Void, Error>]] = [:]
private let tabCreationFactory: (TabStateFactory.CreateTabParams) -> any TabState
let windowId: UUID
/// The property returning only existing tab is NTP for current mode
var isBrowserEmptyForCurrentMode: Bool {
guard tabsForCurrentMode.count == 1,
let tabURL = tabsForCurrentMode.first?.visibleURL,
tabURL.isNewTabURL
else {
return false
}
return true
}
init(
windowId: UUID,
rewards: BraveRewards?,
braveCore: BraveProfileController?,
profile: any Profile,
privateBrowsingManager: PrivateBrowsingManager,
tabCreationFactory: @escaping (TabStateFactory.CreateTabParams) -> any TabState
) {
assert(Thread.isMainThread)
self.windowId = windowId
self.rewards = rewards
self.braveCore = braveCore
self.profile = profile
self.tabGeneratorAPI = braveCore?.tabGeneratorAPI
self.historyAPI = braveCore?.historyAPI
self.privateBrowsingManager = privateBrowsingManager
self.tabCreationFactory = tabCreationFactory
super.init()
Preferences.Chromium.syncOpenTabsEnabled.observe(from: self)
domainFrc.delegate = self
do {
try domainFrc.performFetch()
} catch {
Logger.module.error(
"Failed to perform fetch of Domains for observing dapps permission changes: \(error.localizedDescription, privacy: .public)"
)
}
// Initially fired and set up after tabs are restored
metricsHeartbeat = Timer(
timeInterval: 5.minutes,
repeats: true,
block: { [weak self] _ in
self?.recordTabCountP3A()
}
)
}
deinit {
syncTabsTask?.cancel()
}
var count: Int {
assert(Thread.isMainThread)
return allTabs.count
}
var selectedTab: (any TabState)? {
assert(Thread.isMainThread)
if !(0..<count ~= _selectedIndex) {
return nil
}
return allTabs[_selectedIndex]
}
subscript(index: Int) -> (any TabState)? {
assert(Thread.isMainThread)
if index >= allTabs.count {
return nil
}
return allTabs[index]
}
var currentDisplayedIndex: Int? {
assert(Thread.isMainThread)
guard let selectedTab = self.selectedTab else {
return nil
}
return tabsForCurrentMode.firstIndex(where: { $0 === selectedTab })
}
// What the users sees displayed based on current private browsing mode
var tabsForCurrentMode: [any TabState] {
let isPrivate = privateBrowsingManager.isPrivateBrowsing
return tabs(isPrivate: isPrivate)
}
var openedWebsitesCount: Int {
tabsForCurrentMode.filter {
if let url = $0.visibleURL {
return url.isWebPage()
}
return false
}.count
}
subscript(id: TabState.ID) -> (any TabState)? {
return allTabs.first(where: { $0.id == id })
}
func tabsForCurrentMode(for query: String? = nil) -> [any TabState] {
if let query = query {
let isPrivate = privateBrowsingManager.isPrivateBrowsing
return tabs(isPrivate: isPrivate, query: query)
} else {
return tabsForCurrentMode
}
}
func tabsCountForMode(isPrivate: Bool) -> Int {
return tabs(isPrivate: isPrivate).count
}
private func tabs(isPrivate: Bool, query: String? = nil) -> [any TabState] {
assert(Thread.isMainThread)
let allTabs = allTabs.filter { $0.isPrivate == isPrivate }
if let query = query, !query.isEmpty {
// Display title is the only data that will be present on every situation
return allTabs.filter {
$0.displayTitle.localizedCaseInsensitiveContains(query)
|| ($0.visibleURL?.baseDomain?.localizedCaseInsensitiveContains(query) ?? false)
}
} else {
return allTabs
}
}
/// Function for adding local tabs as synced sessions
/// This is used when open tabs toggle is enabled in sync settings and browser constructor
func addRegularTabsToSyncChain() {
syncTabsTask?.cancel()
syncTabsTask = DispatchWorkItem { [weak self] in
guard let self = self, let task = self.syncTabsTask, !task.isCancelled else {
return
}
let regularTabs = self.tabs(isPrivate: false)
for tab in regularTabs {
if let url = tab.fetchedURL, !tab.isPrivate, !url.isLocal,
!InternalURL.isValid(url: url), !url.isInternalURL(for: .readermode)
{
tab.browserData?.addTabInfoToSyncedSessions(url: url, displayTitle: tab.displayTitle)
}
}
}
if let task = self.syncTabsTask {
DispatchQueue.main.async(execute: task)
}
}
private(set) static var defaultConfiguration = getNewConfiguration(isPrivate: false)
private(set) static var privateConfiguration = getNewConfiguration(isPrivate: true)
private class func getNewConfiguration(isPrivate: Bool = false) -> WKWebViewConfiguration {
assert(
!FeatureList.kUseProfileWebViewConfiguration.enabled,
"Creating a web view configuration with this flag enabled is not valid"
)
let configuration: WKWebViewConfiguration = .init()
configuration.websiteDataStore = isPrivate ? sharedNonPersistentStore() : .default()
configuration.userContentController = WKUserContentController()
configuration.prepareBraveConfiguration()
return configuration
}
func reset() {
if !FeatureList.kUseProfileWebViewConfiguration.enabled {
Self.defaultConfiguration = Self.getNewConfiguration(isPrivate: false)
Self.privateConfiguration = Self.getNewConfiguration(isPrivate: true)
}
for tab in allTabs {
if tab.isWebViewCreated {
tab.deleteWebView()
}
}
}
func clearTabHistory(_ completion: (() -> Void)? = nil) {
allTabs.filter({ $0.isWebViewCreated }).forEach({
$0.clearBackForwardList()
SessionTab.update(
tabId: $0.id,
interactionState: $0.sessionData ?? Data(),
title: $0.title ?? "",
url: $0.visibleURL ?? TabManager.ntpInteralURL
)
})
completion?()
}
func reloadSelectedTab() {
let tab = selectedTab
_selectedIndex = -1
selectTab(tab)
if let url = selectedTab?.visibleURL {
selectedTab?.loadRequest(PrivilegedRequest(url: url) as URLRequest)
}
}
func selectTab(_ tab: (any TabState)?, previous: (any TabState)? = nil) {
assert(Thread.isMainThread)
let previous = previous ?? selectedTab
if previous === tab {
return
}
// Convert the global mode to normal/private
privateBrowsingManager.isPrivateBrowsing = tab?.isPrivate == true
// Make sure to wipe the private tabs if the user has the pref turned on
if tab?.isPrivate == false
&& (Preferences.Privacy.privateBrowsingOnly.value
|| !Preferences.Privacy.persistentPrivateBrowsing.value)
{
removeAllPrivateTabs()
}
if let tab = tab {
_selectedIndex = allTabs.firstIndex(where: { $0 === tab }) ?? -1
} else {
_selectedIndex = -1
}
if let previousTab = previous {
preserveScreenshot(for: previousTab)
}
if let t = selectedTab, !t.isWebViewCreated, t.opener == nil {
selectedTab?.createWebView()
}
guard tab === selectedTab else {
Logger.module.error(
"Expected tab (\(tab?.visibleURL?.absoluteString ?? "nil")) is not selected. Selected index: \(self.selectedIndex)"
)
return
}
if let tabId = tab?.id {
SessionTab.setSelected(tabId: tabId)
}
UIImpactFeedbackGenerator(style: .light).vibrate()
if let selectedTab = selectedTab,
selectedTab.lastCommittedURL == nil,
!selectedTab.isLoading
{
// Realize a zombie tab with restoration data
restoreTab(selectedTab)
}
delegates.forEach { $0.get()?.tabManager(self, didSelectedTabChange: tab, previous: previous) }
if let tab = previous {
tab.isVisible = false
}
if let tab = selectedTab {
tab.isVisible = true
}
if let tabID = tab?.id {
SessionTab.touch(tabId: tabID)
}
guard let newSelectedTab = tab, let previousTab = previous,
let newTabUrl = newSelectedTab.visibleURL
else { return }
if !privateBrowsingManager.isPrivateBrowsing {
if previousTab.faviconTabHelper?.displayFavicon == nil {
adsRewardsLog.warning("No favicon found in tab to report to rewards panel")
}
rewards?.reportTabUpdated(
tab: previousTab,
isSelected: false,
isPrivate: previousTab.isPrivate
)
if newSelectedTab.faviconTabHelper?.displayFavicon == nil && !newTabUrl.isLocal {
adsRewardsLog.warning("No favicon found in tab to report to rewards panel")
}
rewards?.reportTabUpdated(
tab: newSelectedTab,
isSelected: true,
isPrivate: newSelectedTab.isPrivate
)
}
}
// Called by other classes to signal that they are entering/exiting private mode
// This is called by TabTrayVC when the private mode button is pressed and BEFORE we've switched to the new mode
// we only want to remove all private tabs when leaving PBM and not when entering.
func willSwitchTabMode(leavingPBM: Bool) {
if leavingPBM {
if Preferences.Privacy.privateBrowsingOnly.value
|| !Preferences.Privacy.persistentPrivateBrowsing.value
{
removeAllPrivateTabs()
}
}
}
/// Called to turn selectedIndex back to -1
func resetSelectedIndex() {
_selectedIndex = -1
}
@MainActor func addPopupForParentTab(
_ parentTab: any TabState
) -> any TabState {
var wkConfiguration: WKWebViewConfiguration?
if !FeatureList.kUseProfileWebViewConfiguration.enabled {
wkConfiguration = parentTab.configuration
}
let popup = tabCreationFactory(
.init(
profile: parentTab.profile,
initialConfiguration: wkConfiguration
)
)
configureTab(
popup,
request: nil,
afterTab: parentTab,
flushToDisk: true,
zombie: true,
isPopup: true
)
return popup
}
@discardableResult
@MainActor func addTabAndSelect(
_ request: URLRequest! = nil,
afterTab: (any TabState)? = nil,
isPrivate: Bool
) -> any TabState {
let tab = addTab(request, afterTab: afterTab, isPrivate: isPrivate)
selectTab(tab)
return tab
}
@MainActor func addTabsForURLs(_ urls: [URL], isPrivate: Bool = false) {
assert(Thread.isMainThread)
if urls.isEmpty {
return
}
// When bulk adding tabs don't notify delegates until we are done
self.isRestoring = true
var tabs = [any TabState]()
for url in urls {
let request =
InternalURL.isValid(url: url)
? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url)
let tab = self.addTab(
request,
flushToDisk: false,
zombie: true,
isPrivate: isPrivate
)
tab.lastTitle = url.absoluteDisplayString
tab.setVirtualURL(url)
tabs.append(tab)
}
// Select the most recent.
self.selectTab(tabs.last)
self.isRestoring = false
// Okay now notify that we bulk-loaded so we can adjust counts and animate changes.
delegates.forEach { $0.get()?.tabManagerDidAddTabs(self) }
}
@discardableResult
@MainActor func addTab(
_ request: URLRequest? = nil,
afterTab: (any TabState)? = nil,
flushToDisk: Bool = true,
zombie: Bool = false,
id: UUID? = nil,
lastActiveTime: Date? = nil,
isPrivate: Bool
) -> any TabState {
assert(Thread.isMainThread)
let tabId = id ?? UUID()
var initialConfiguration: WKWebViewConfiguration?
if !FeatureList.kUseProfileWebViewConfiguration.enabled {
initialConfiguration = isPrivate ? Self.privateConfiguration : Self.defaultConfiguration
}
let tab = tabCreationFactory(
.init(
id: tabId,
profile: isPrivate ? profile.offTheRecordProfile : profile,
initialConfiguration: initialConfiguration,
lastActiveTime: lastActiveTime
)
)
configureTab(
tab,
request: request,
afterTab: afterTab,
flushToDisk: flushToDisk,
zombie: zombie
)
return tab
}
func moveTab(_ tab: some TabState, toIndex visibleToIndex: Int) {
assert(Thread.isMainThread)
let currentTabs = tabs(isPrivate: tab.isPrivate)
let toTab = currentTabs[visibleToIndex]
guard let fromIndex = allTabs.firstIndex(where: { $0 === tab }),
let toIndex = allTabs.firstIndex(where: { $0 === toTab })
else {
return
}
// Make sure to save the selected tab before updating the tabs list
let previouslySelectedTab = selectedTab
let tab = allTabs.remove(at: fromIndex)
allTabs.insert(tab, at: toIndex)
if let previouslySelectedTab = previouslySelectedTab,
let previousSelectedIndex = allTabs.firstIndex(where: { $0 === previouslySelectedTab })
{
_selectedIndex = previousSelectedIndex
}
saveTabOrder()
}
func moveTabs(_ tabs: [TabState.ID], toIndex index: Int) {
assert(Thread.isMainThread)
let tabsToMove = tabs.compactMap { id in
allTabs.first(where: { $0.id == id })
}
let isPrivate = tabsToMove.first?.isPrivate ?? false
guard !tabsToMove.isEmpty, tabsToMove.allSatisfy({ $0.isPrivate == isPrivate }) else { return }
// Save the selected tab before updating the tabs list
let previouslySelectedTab = selectedTab
// Remove all tabs to move from their current positions (in reverse order to maintain indices)
var removedTabs: [any TabState] = []
for tabToMove in tabsToMove.reversed() {
if let fromIndex = allTabs.firstIndex(where: { $0 === tabToMove }) {
let tab = allTabs.remove(at: fromIndex)
removedTabs.insert(tab, at: 0)
}
}
// Calculate insertion index in the current mode tabs after removals
let currentTabsAfterRemovals = tabsForCurrentMode
let insertionIndex = min(index, currentTabsAfterRemovals.count)
// Find the corresponding index in allTabs
let adjustedIndex: Int
if insertionIndex >= currentTabsAfterRemovals.count {
// Insert at the end of this mode's tabs
adjustedIndex = allTabs.count
} else {
// Insert before the tab at the insertion index
let targetTab = currentTabsAfterRemovals[insertionIndex]
adjustedIndex = allTabs.firstIndex(where: { $0 === targetTab }) ?? allTabs.count
}
// Insert all tabs at the target position
allTabs.insert(contentsOf: removedTabs, at: adjustedIndex)
// Restore the selected index if needed
if let previouslySelectedTab = previouslySelectedTab,
let previousSelectedIndex = allTabs.firstIndex(where: { $0 === previouslySelectedTab })
{
_selectedIndex = previousSelectedIndex
}
saveTabOrder()
}
private func saveTabOrder() {
if Preferences.Privacy.privateBrowsingOnly.value
|| (privateBrowsingManager.isPrivateBrowsing
&& !Preferences.Privacy.persistentPrivateBrowsing.value)
{
return
}
let allTabIds = allTabs.compactMap { $0.id }
SessionTab.saveTabOrder(tabIds: allTabIds)
}
@MainActor func configureTab(
_ tab: some TabState,
request: URLRequest?,
afterTab parent: (any TabState)? = nil,
flushToDisk: Bool,
zombie: Bool,
isPopup: Bool = false
) {
assert(Thread.isMainThread)
var request = request
let isPrivate = tab.isPrivate
let isPersistentTab =
!isPrivate
|| (isPrivate && !Preferences.Privacy.privateBrowsingOnly.value
&& Preferences.Privacy.persistentPrivateBrowsing.value)
// WebKit can sometimes return a URL that isn't valid at all!
// Do not allow configuring a tab with a Bookmarklet or Javascript URL
if let requestURL = request?.url,
NSURL(idnString: requestURL.absoluteString) == nil || requestURL.isBookmarklet
{
request?.url = TabManager.aboutBlankBlockedURL
}
if isPersistentTab {
SessionTab.createIfNeeded(
windowId: windowId,
tabId: tab.id,
title: Strings.newTab,
tabURL: request?.url ?? TabManager.ntpInteralURL,
isPrivate: isPrivate
)
}
delegates.forEach { $0.get()?.tabManager(self, willAddTab: tab) }
if parent == nil || parent?.isPrivate != tab.isPrivate {
allTabs.append(tab)
} else if let parent = parent, var insertIndex = allTabs.firstIndex(where: { $0 === parent }) {
insertIndex += 1
while insertIndex < allTabs.count && allTabs[insertIndex].isDescendentOf(parent) {
insertIndex += 1
}
if isPopup {
tab.opener = parent
} else {
tab.orderingParent = parent
}
allTabs.insert(tab, at: insertIndex)
}
delegates.forEach { $0.get()?.tabManager(self, didAddTab: tab) }
if !zombie {
tab.createWebView()
if let request = request {
tab.loadRequest(request)
} else if !isPopup {
tab.loadRequest(PrivilegedRequest(url: TabManager.ntpInteralURL) as URLRequest)
}
} else {
// Set virtual urls for unrealized/zombie tabs
if let request = request {
tab.setVirtualURL(request.url)
} else if !isPopup {
tab.setVirtualURL(TabManager.ntpInteralURL)
}
}
// Ignore on restore.
if flushToDisk && !zombie && isPersistentTab {
saveTab(tab, saveOrder: true)
}
}
func saveAllTabs(synchronously: Bool = false) {
if Preferences.Privacy.privateBrowsingOnly.value
|| (privateBrowsingManager.isPrivateBrowsing
&& !Preferences.Privacy.persistentPrivateBrowsing.value)
{
return
}
let tabs =
Preferences.Privacy.persistentPrivateBrowsing.value ? allTabs : tabs(isPrivate: false)
SessionTab.updateAll(
synchronously: synchronously,
tabs: tabs.compactMap({
if let sessionData = $0.sessionData {
return ($0.id, sessionData, $0.title ?? "", $0.visibleURL ?? TabManager.ntpInteralURL)
}
return nil
})
)
}
func saveTab(_ tab: some TabState, saveOrder: Bool = false) {
if Preferences.Privacy.privateBrowsingOnly.value
|| (tab.isPrivate && !Preferences.Privacy.persistentPrivateBrowsing.value)
{
return
}
SessionTab.update(
tabId: tab.id,
interactionState: tab.sessionData ?? Data(),
title: tab.title ?? "",
url: tab.visibleURL ?? TabManager.ntpInteralURL
)
if saveOrder {
saveTabOrder()
}
}
/// Forget all data for websites that have forget me enabled
/// Will forget all data instantly with no delay
func forgetDataOnAppExitDomains() {
guard BraveCore.FeatureList.kBraveShredFeature.enabled else { return }
Task { @MainActor in
var shredOnAppExitURLs: [URL] = []
if FeatureList.kBraveShieldsContentSettings.enabled {
guard let braveShieldsSettings = BraveShieldsSettingsServiceFactory.get(profile: profile)
else { return }
// iterate over WKWebsiteDataStore data records
let dataRecords = await WKWebsiteDataStore.default().dataRecords(
ofTypes: WKWebsiteDataStore.allWebsiteDataTypesIncludingPrivate()
)
shredOnAppExitURLs = dataRecords.compactMap { record in
guard let url = URL(string: "https://" + record.displayName),
braveShieldsSettings.autoShredMode(for: url, considerAllShieldsOption: true) == .appExit
else {
return nil
}
return url
}
if Preferences.Shields.shredHistoryItems.value {
// if user enabled shred and/or shred history but does not have data
// in WKWebsiteDataStore, we still need to shred it.
if let historyNodes = await historyAPI?.search(
withQuery: nil,
options: HistorySearchOptions(
maxCount: 0,
hostOnly: false,
duplicateHandling: .removeAll,
begin: nil,
end: nil
)
) {
for node in historyNodes {
if braveShieldsSettings.autoShredMode(for: node.url) == .appExit {
shredOnAppExitURLs.append(node.url)
}
}
}
// Similar to history above for Recently Closed tabs
for tab in RecentlyClosed.all() {
if let url = URL(string: tab.url),
braveShieldsSettings.autoShredMode(for: url) == .appExit
{
shredOnAppExitURLs.append(url)
}
}
}
} else { // kBraveShieldsContentSettings disabled
shredOnAppExitURLs = await Domain.allURLsWithShredLevel(
rawShredLevel: SiteShredLevel.appExit.rawValue,
isGlobalShredLevel: Preferences.Shields.shredLevel.shredOnAppExit
)
}
guard !shredOnAppExitURLs.isEmpty else { return }
await forgetData(for: shredOnAppExitURLs)
}
}
/// Forget all data for websites if the website has Auto Shred set to site
/// tabs closed. A delay allows us to cancel this Auto Shred in case the user goes back to
/// this website.
///
/// - Parameters:
/// - url: The url of the website to forget
/// - tab: The tab in which the website is or was open in
/// - delayInSeconds: Only attempt to forget the content after a short delay (default: 30s)
/// - checkOtherTabs: Check if other tabs are open for the given domain
@MainActor func forgetDataIfNeeded(
for url: URL,
in tab: some TabState
) {
guard FeatureList.kBraveShredFeature.enabled else { return }
guard let url = url.urlToShred,
let baseDomain = url.baseDomain
else { return }
forgetTasks[tab.isPrivate]?[baseDomain]?.cancel()
let shredLevel =
tab.braveShieldsHelper?.shredLevel(
for: url,
considerAllShieldsOption: true
) ?? .never
switch shredLevel {
case .never:
return
case .appExit:
// Will be Shred on startup at next launch in `forgetDataOnAppExitDomains()`.
return
case .whenSiteClosed:
let tabs = tabs(isPrivate: tab.isPrivate).filter { existingTab in
existingTab !== tab
}
// Ensure that no othe tabs are open for this domain
guard !tabs.contains(where: { $0.visibleURL?.urlToShred?.baseDomain == baseDomain })
else {
return
}
forgetDataDelayed(for: url, in: tab, delay: 30)
}
}
private var websiteDataStoreForCurrentMode: WKWebsiteDataStore {
let isPrivateBrowsing = privateBrowsingManager.isPrivateBrowsing
if FeatureList.kUseProfileWebViewConfiguration.enabled, let braveCore {
let configuration =
isPrivateBrowsing
? braveCore.defaultWebViewConfiguration : braveCore.nonPersistentWebViewConfiguration
return configuration.websiteDataStore
} else {
let configuration = isPrivateBrowsing ? Self.privateConfiguration : Self.defaultConfiguration
return configuration.websiteDataStore
}
}
/// Shreds data for a set of tabs and returns tabs that are to be shredded/removed.
@MainActor func shredDataForTabs(_ tabs: [any TabState]) -> Set<TabState.ID> {
let isPrivateBrowsing = privateBrowsingManager.isPrivateBrowsing
let urlsToShred = Set(tabs.compactMap(\.visibleURL?.urlToShred))
let tabsToRemove = self.tabs(isPrivate: isPrivateBrowsing).filter({
if let url = $0.visibleURL?.urlToShred {
return urlsToShred.contains(url)
}
return false
})
Task {
removeTabs(tabsToRemove)
await forgetData(for: Array(urlsToShred), dataStore: websiteDataStoreForCurrentMode)
}
return Set(tabsToRemove.map(\.id))
}
@MainActor func shredAllTabsForCurrentMode() {
let isPrivateBrowsing = privateBrowsingManager.isPrivateBrowsing
let urlsToShred = Set(tabs(isPrivate: isPrivateBrowsing).compactMap(\.visibleURL))
Task {
removeAllTabsForPrivateMode(isPrivate: isPrivateBrowsing)
await forgetData(for: Array(urlsToShred), dataStore: websiteDataStoreForCurrentMode)
}
}
@MainActor func shredData(for url: URL, in tab: some TabState) {
guard let url = url.urlToShred,
let baseDomain = url.baseDomain
else { return }
// Select the next or previous tab that is not being destroyed
if let index = allTabs.firstIndex(where: { $0 === tab }) {
var nextTab: (any TabState)?
// First seach down or up for a tab that is not being destroyed
var increasingIndex = index + 1
while nextTab == nil, increasingIndex < allTabs.count {
if allTabs[increasingIndex].visibleURL?.urlToShred?.baseDomain != baseDomain
&& allTabs[increasingIndex].isPrivate == tab.isPrivate
{
nextTab = allTabs[increasingIndex]
}
increasingIndex += 1
}
var decreasingIndex = index - 1
while nextTab == nil, decreasingIndex > 0 {
if allTabs[decreasingIndex].visibleURL?.urlToShred?.baseDomain != baseDomain
&& allTabs[decreasingIndex].isPrivate == tab.isPrivate
{
nextTab = allTabs[decreasingIndex]
}
decreasingIndex -= 1
}
// Select the found tab
if let nextTab = nextTab {
selectTab(nextTab, previous: tab)
}
}
// Remove all unwanted tabs
for tabToClose in allTabs
where tabToClose.visibleURL?.urlToShred?.baseDomain == baseDomain
&& tabToClose.isPrivate == tab.isPrivate
{
// The Tab's WebView is not deinitialized immediately, so it's possible the
// WebView still stores data after we shred but before the WebView is deinitialized.
// Delete the web view to prevent data being stored after data is Shred.
tabToClose.deleteWebView()
removeTab(tabToClose)
}
Task {
// Forget all the data
await forgetData(for: url, in: tab)
}
}
/// Start a task to delete all data for this url
/// The task may be delayed in case we want to cancel it
@MainActor private func forgetDataDelayed(
for url: URL,
in tab: some TabState,
delay: TimeInterval
) {
guard let url = url.urlToShred,
let baseDomain = url.baseDomain
else { return }
forgetTasks[tab.isPrivate] = forgetTasks[tab.isPrivate] ?? [:]
// Start a task to delete all data for this etldP1
// The task may be delayed in case we want to cancel it
forgetTasks[tab.isPrivate]?[baseDomain] = Task {
try await Task.sleep(seconds: delay)
await self.forgetData(for: url, in: tab)
}
}
@MainActor private func forgetData(for url: URL, in tab: (any TabState)?) async {
await forgetData(for: [url], dataStore: tab?.configuration?.websiteDataStore)
ContentBlockerManager.log.debug("Cleared website data for `\(url.baseDomain ?? "")`")
if let baseDomain = url.baseDomain, let tab {
forgetTasks[tab.isPrivate]?.removeValue(forKey: baseDomain)
}
}
@MainActor private func forgetData(for urls: [URL], dataStore: WKWebsiteDataStore? = nil) async {
let urls = urls.compactMap(\.urlToShred)
let baseDomains = Set(urls.compactMap { $0.baseDomain })
guard !baseDomains.isEmpty else { return }
let dataStore = dataStore ?? WKWebsiteDataStore.default()
// Delete 1P data records
await dataStore.deleteDataRecords(
forDomains: baseDomains
)
if BraveCore.FeatureList.kBraveShredCacheData.enabled {
// Delete all cache data (otherwise 3P cache entries left behind
// are visible in Manage Website Data view brave-browser #41095)
let cacheTypes = Set([
WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache,
WKWebsiteDataTypeOfflineWebApplicationCache,
])
let cacheRecords = await dataStore.dataRecords(ofTypes: cacheTypes)
await dataStore.removeData(ofTypes: cacheTypes, for: cacheRecords)
}
// Delete the history for forgotten websites
if let historyAPI = self.historyAPI, Preferences.Shields.shredHistoryItems.value {
// if we're only forgetting 1 site, we can query history by it's domain
let query = urls.count == 1 ? urls.first?.baseDomain : nil
let nodes = await historyAPI.search(
withQuery: query,
options: HistorySearchOptions(
maxCount: 0,
hostOnly: false,
duplicateHandling: .keepAll,
begin: nil,
end: nil
)
).filter { node in
guard let baseDomain = node.url.baseDomain else { return false }
return baseDomains.contains(baseDomain)
}
historyAPI.removeHistory(for: nodes)
}
if Preferences.Shields.shredHistoryItems.value {