-
Notifications
You must be signed in to change notification settings - Fork 406
/
TabManager.swift
326 lines (267 loc) · 10.8 KB
/
TabManager.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
//
// TabManager.swift
// DuckDuckGo
//
// Copyright © 2017 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 Common
import Core
import DDGSync
import WebKit
import BrowserServicesKit
import Persistence
import History
class TabManager {
private(set) var model: TabsModel
private var tabControllerCache = [TabViewController]()
private let bookmarksDatabase: CoreDataDatabase
private let historyManager: HistoryManager
private let syncService: DDGSyncing
private var previewsSource: TabPreviewsSource
weak var delegate: TabDelegate?
@UserDefaultsWrapper(key: .faviconTabsCacheNeedsCleanup, defaultValue: true)
var tabsCacheNeedsCleanup: Bool
@MainActor
init(model: TabsModel,
previewsSource: TabPreviewsSource,
bookmarksDatabase: CoreDataDatabase,
historyManager: HistoryManager,
syncService: DDGSyncing) {
self.model = model
self.previewsSource = previewsSource
self.bookmarksDatabase = bookmarksDatabase
self.historyManager = historyManager
self.syncService = syncService
registerForNotifications()
}
@MainActor
private func buildController(forTab tab: Tab, inheritedAttribution: AdClickAttributionLogic.State?) -> TabViewController {
let url = tab.link?.url
return buildController(forTab: tab, url: url, inheritedAttribution: inheritedAttribution)
}
@MainActor
private func buildController(forTab tab: Tab, url: URL?, inheritedAttribution: AdClickAttributionLogic.State?) -> TabViewController {
let configuration = WKWebViewConfiguration.persistent()
let controller = TabViewController.loadFromStoryboard(model: tab,
bookmarksDatabase: bookmarksDatabase,
historyManager: historyManager,
syncService: syncService)
controller.applyInheritedAttribution(inheritedAttribution)
controller.attachWebView(configuration: configuration,
andLoadRequest: url == nil ? nil : URLRequest.userInitiated(url!),
consumeCookies: !model.hasActiveTabs)
controller.delegate = delegate
controller.loadViewIfNeeded()
return controller
}
@MainActor
func current(createIfNeeded: Bool = false) -> TabViewController? {
let index = model.currentIndex
let tab = model.tabs[index]
if let controller = controller(for: tab) {
return controller
} else if createIfNeeded {
os_log("Tab not in cache, creating", log: .generalLog, type: .debug)
let controller = buildController(forTab: tab, inheritedAttribution: nil)
tabControllerCache.append(controller)
return controller
} else {
return nil
}
}
private func controller(for tab: Tab) -> TabViewController? {
return tabControllerCache.first { $0.tabModel === tab }
}
var isEmpty: Bool {
return tabControllerCache.isEmpty
}
var hasUnread: Bool {
return model.hasUnread
}
var count: Int {
return model.count
}
@MainActor
func select(tabAt index: Int) -> TabViewController {
current()?.dismiss()
model.select(tabAt: index)
save()
return current(createIfNeeded: true)!
}
func addURLRequest(_ request: URLRequest?,
with configuration: WKWebViewConfiguration,
inheritedAttribution: AdClickAttributionLogic.State?) -> TabViewController {
guard let configCopy = configuration.copy() as? WKWebViewConfiguration else {
fatalError("Failed to copy configuration")
}
let tab: Tab
if let request {
tab = Tab(link: request.url == nil ? nil : Link(title: nil, url: request.url!))
} else {
tab = Tab()
}
model.insert(tab: tab, at: model.currentIndex + 1)
model.select(tabAt: model.currentIndex + 1)
let controller = TabViewController.loadFromStoryboard(model: tab,
bookmarksDatabase: bookmarksDatabase,
historyManager: historyManager,
syncService: syncService)
controller.attachWebView(configuration: configCopy,
andLoadRequest: request,
consumeCookies: !model.hasActiveTabs,
loadingInitiatedByParentTab: true)
controller.delegate = delegate
controller.loadViewIfNeeded()
controller.applyInheritedAttribution(inheritedAttribution)
tabControllerCache.append(controller)
save()
return controller
}
func addHomeTab() {
model.add(tab: Tab())
model.select(tabAt: model.count - 1)
save()
}
func firstHomeTab() -> Tab? {
return model.tabs.first(where: { $0.link == nil })
}
func first(withUrl url: URL) -> Tab? {
return model.tabs.first(where: {
guard let linkUrl = $0.link?.url else { return false }
if linkUrl == url {
return true
}
if linkUrl.scheme == "https" && url.scheme == "http" {
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
components?.scheme = "https"
return components?.url == linkUrl
}
return false
})
}
func selectTab(_ tab: Tab) {
guard let index = model.indexOf(tab: tab) else { return }
model.select(tabAt: index)
save()
}
@MainActor
func add(url: URL?, inBackground: Bool = false, inheritedAttribution: AdClickAttributionLogic.State?) -> TabViewController {
if !inBackground {
current()?.dismiss()
}
let link = url == nil ? nil : Link(title: nil, url: url!)
let tab = Tab(link: link)
let controller = buildController(forTab: tab, url: url, inheritedAttribution: inheritedAttribution)
tabControllerCache.append(controller)
let index = model.currentIndex
model.insert(tab: tab, at: index + 1)
if !inBackground {
model.select(tabAt: index + 1)
}
save()
return controller
}
func remove(at index: Int) {
let tab = model.get(tabAt: index)
previewsSource.removePreview(forTab: tab)
model.remove(tab: tab)
if let controller = controller(for: tab) {
removeFromCache(controller)
}
save()
}
private func removeFromCache(_ controller: TabViewController) {
if let index = tabControllerCache.firstIndex(of: controller) {
tabControllerCache.remove(at: index)
}
controller.dismiss()
}
func removeAll() {
previewsSource.removeAllPreviews()
model.clearAll()
for controller in tabControllerCache {
removeFromCache(controller)
}
save()
}
@MainActor
func invalidateCache(forController controller: TabViewController) {
if current() === controller {
Pixel.fire(pixel: .webKitTerminationDidReloadCurrentTab)
current()?.reload()
} else {
removeFromCache(controller)
}
}
func save() {
model.save()
}
@MainActor
func prepareAllTabsExceptCurrentForDataClearing() {
tabControllerCache.filter { $0 !== current() }.forEach { $0.prepareForDataClearing() }
}
@MainActor
func prepareCurrentTabForDataClearing() {
current()?.prepareForDataClearing()
}
func cleanupTabsFaviconCache() {
guard tabsCacheNeedsCleanup else { return }
DispatchQueue.global(qos: .background).async { [weak self] in
guard let self = self,
let tabsCacheUrl = Favicons.CacheType.tabs.cacheLocation()?.appendingPathComponent(Favicons.Constants.tabsCachePath),
let contents = try? FileManager.default.contentsOfDirectory(at: tabsCacheUrl, includingPropertiesForKeys: nil, options: []),
!contents.isEmpty else { return }
let imageDomainURLs = contents.compactMap({ $0.filename })
// create a Set of all unique hosts in case there are hundreds of tabs with many duplicate hosts
let tabLink = Set(self.model.tabs.compactMap { tab in
if let host = tab.link?.url.host {
return host
}
return nil
})
// hash the unique tab hosts
let tabLinksHashed = tabLink.map { Favicons.createHash(ofDomain: $0) }
// filter images that don't have a corresponding tab
let toDelete = imageDomainURLs.filter { !tabLinksHashed.contains($0) }
toDelete.forEach {
Favicons.shared.removeTabFavicon(forCacheKey: $0)
}
self.tabsCacheNeedsCleanup = false
}
}
}
// MARK: - Debugging Pixels
extension TabManager {
fileprivate func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(onApplicationBecameActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
@objc
private func onApplicationBecameActive(_ notification: NSNotification) {
assertTabPreviewCount()
}
private func assertTabPreviewCount() {
let totalStoredPreviews = previewsSource.totalStoredPreviews()
let totalTabs = model.tabs.count
if let storedPreviews = totalStoredPreviews, storedPreviews > totalTabs {
Pixel.fire(pixel: .cachedTabPreviewsExceedsTabCount, withAdditionalParameters: [
PixelParameters.tabPreviewCountDelta: "\(storedPreviews - totalTabs)"
])
TabPreviewsCleanup.shared.startCleanup(with: model, source: previewsSource)
}
}
}