This repository was archived by the owner on Feb 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathWebExtensionManager.swift
371 lines (293 loc) · 14.8 KB
/
WebExtensionManager.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
//
// WebExtensionManager.swift
//
// Copyright © 2023 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 Foundation
import Common
import WebKit
import os.log
import BrowserServicesKit
@available(macOS 14.4, *)
protocol WebExtensionManaging {
var areExtenstionsEnabled: Bool { get }
// Adding and removing extensions
var webExtensionPaths: [String] { get }
func addExtension(path: String)
func removeExtension(path: String)
// Provides the extension name for the extension resource base path
func extensionName(from path: String) -> String?
// Controller for tabs
var controller: _WKWebExtensionController? { get }
// Listening of events
var eventsListener: WebExtensionEventsListening { get }
}
// Manages the initialization and ownership of key components: web extensions, contexts, and the controller
@available(macOS 14.4, *)
final class WebExtensionManager: NSObject, WebExtensionManaging {
static let shared = WebExtensionManager()
init(webExtensionPathsCache: WebExtensionPathsCaching = WebExtensionPathsCache(),
webExtensionLoader: WebExtensionLoading = WebExtensionLoader(),
internalUserDecider: InternalUserDecider = NSApp.delegateTyped.internalUserDecider,
featureFlagger: FeatureFlagger = NSApp.delegateTyped.featureFlagger) {
self.pathsCache = webExtensionPathsCache
self.internalUserDecider = internalUserDecider
self.featureFlagger = featureFlagger
self.loader = webExtensionLoader
super.init()
internalSiteHandler.dataSource = self
do {
try loadWebExtensions()
} catch {
assertionFailure("Failed to load web extensions")
}
}
private let internalUserDecider: InternalUserDecider
private let featureFlagger: FeatureFlagger
var areExtenstionsEnabled: Bool {
internalUserDecider.isInternalUser && featureFlagger.isFeatureOn(.webExtensions)
}
// Caches paths to selected web extensions
var pathsCache: WebExtensionPathsCaching
// Loads web extensions after selection or application start
var loader: WebExtensionLoading
// Loaded extensions
var extensions: [_WKWebExtension] = []
// Context manages the extension's permissions and allows it to inject content, run background logic, show popovers, and display other web-based UI to the user.
var contexts: [_WKWebExtensionContext] = []
// Controller manages a set of loaded extension contexts
var controller: _WKWebExtensionController?
// Events listening
var eventsListener: WebExtensionEventsListening = WebExtensionEventsListener()
// Handles native messaging
let nativeMessagingHandler = NativeMessagingHandler()
// Handles internal sites of web extenions
let internalSiteHandler = WebExtensionInternalSiteHandler()
// MARK: - Adding and removing extensions
var webExtensionPaths: [String] {
pathsCache.cache
}
func addExtension(path: String) {
pathsCache.add(path)
}
func removeExtension(path: String) {
pathsCache.remove(path)
}
func extensionName(from path: String) -> String? {
if let extensionURL = URL(string: path) {
return try? _WKWebExtension(resourceBaseURL: extensionURL).displayName
}
return nil
}
// MARK: - Lifecycle
private func loadWebExtensions() throws {
guard areExtenstionsEnabled else { return }
// Load extensions
extensions = loader.loadWebExtensions(from: pathsCache.cache)
// Make contexts
contexts = extensions.map {
makeContext(for: $0)
}
// Make controller and load extension contexts
let controller = _WKWebExtensionController()
try contexts.forEach {
try controller.loadExtensionContext($0)
}
controller.delegate = self
eventsListener.controller = controller
self.controller = controller
}
private func makeContext(for webExtension: _WKWebExtension) -> _WKWebExtensionContext {
let context = _WKWebExtensionContext(for: webExtension)
// Temporary fix to have the same state on multiple browser sessions
context.uniqueIdentifier = UUID(uuidString: "36dbd1f8-27c7-43fd-a206-726958a1018d")!.uuidString
// In future, we should grant only what the extension requests.
let matchPatterns = context.webExtension.allRequestedMatchPatterns
for pattern in matchPatterns {
context.setPermissionStatus(.grantedExplicitly, for: pattern, expirationDate: nil)
}
let permissions: [String] = ["activeTab", "alarms", "clipboardWrite", "contextMenus", "cookies", "declarativeNetRequest", "declarativeNetRequestFeedback", "declarativeNetRequestWithHostAccess", "menus", "nativeMessaging", "notifications", "scripting", "sidePanel", "storage", "tabs", "unlimitedStorage", "webNavigation", "webRequest"]
for permission in permissions {
context.setPermissionStatus(.grantedExplicitly, for: permission, expirationDate: nil)
}
// For debugging purposes
context.isInspectable = true
return context
}
// MARK: - UI
static let buttonSize: CGFloat = 28
func toolbarButtons() -> [MouseOverButton] {
return contexts.enumerated().map { (index, context) in
let image = context.webExtension.icon(for: CGSize(width: Self.buttonSize, height: Self.buttonSize)) ?? NSImage(named: "Web")!
let button = MouseOverButton(image: image, target: self, action: #selector(WebExtensionManager.toolbarButtonClicked))
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: Self.buttonSize).isActive = true
button.heightAnchor.constraint(equalToConstant: Self.buttonSize).isActive = true
button.tag = index
return button
}
}
@MainActor
@objc func toolbarButtonClicked(sender: NSButton) {
let index = sender.tag
let context = contexts[index]
// If the popover is already open
if let popover = context.action(for: nil)?.popupPopover, popover.isShown {
// Close it
popover.close()
// If the sender button is in a different window, open the popover there
if sender.window != popover.mainWindow {
DispatchQueue.main.asyncAfter(deadline: .now() + 2/3) {
context.performAction(for: nil)
}
}
return
}
// Show dashboard - perform default action
context.performAction(for: nil)
}
@MainActor
func buttonForContext(_ context: _WKWebExtensionContext) -> NSButton? {
guard let index = contexts.firstIndex(of: context) else {
assertionFailure("Unknown context")
return nil
}
guard let mainWindowController = WindowControllersManager.shared.lastKeyMainWindowController else {
assertionFailure("No main window controller")
return nil
}
let button = mainWindowController.mainViewController.navigationBarViewController.menuButtons.arrangedSubviews[index] as? NSButton
return button
}
}
@available(macOS 14.4, *)
@MainActor
extension WebExtensionManager: @preconcurrency _WKWebExtensionControllerDelegate {
enum WKWebExtensionControllerDelegateError: Error {
case notSupported
}
func webExtensionController(_ controller: _WKWebExtensionController, openWindowsFor extensionContext: _WKWebExtensionContext) -> [any _WKWebExtensionWindow] {
var windows = WindowControllersManager.shared.mainWindowControllers
if let focusedWindow = WindowControllersManager.shared.lastKeyMainWindowController {
// Ensure focusedWindow is the first item
windows.removeAll { $0 === focusedWindow }
windows.insert(focusedWindow, at: 0)
}
return windows
}
func webExtensionController(_ controller: _WKWebExtensionController, focusedWindowFor extensionContext: _WKWebExtensionContext) -> (any _WKWebExtensionWindow)? {
return WindowControllersManager.shared.lastKeyMainWindowController
}
func webExtensionController(_ controller: _WKWebExtensionController, openNewWindowWith options: _WKWebExtensionWindowCreationOptions, for extensionContext: _WKWebExtensionContext) async throws -> (any _WKWebExtensionWindow)? {
// Extract options
let tabs = options.desiredURLs.map { Tab(content: .contentFromURL($0, source: .ui)) }
let burnerMode = BurnerMode(isBurner: options.shouldUsePrivateBrowsing)
let tabCollectionViewModel = TabCollectionViewModel(
tabCollection: TabCollection(tabs: tabs),
burnerMode: burnerMode
)
// Create new window
let mainWindow = WindowControllersManager.shared.openNewWindow(
with: tabCollectionViewModel,
burnerMode: burnerMode,
droppingPoint: options.desiredFrame.origin,
contentSize: options.desiredFrame.size,
showWindow: options.shouldFocus,
popUp: options.desiredWindowType == .popup,
isMiniaturized: options.desiredWindowState == .minimized,
isMaximized: options.desiredWindowState == .maximized,
isFullscreen: options.desiredWindowState == .fullscreen
)
// Move existing tabs if necessary
try moveExistingTabs(options.desiredTabs, to: tabCollectionViewModel)
return mainWindow?.windowController as? MainWindowController
}
private func moveExistingTabs(_ existingTabs: [any _WKWebExtensionTab], to targetViewModel: TabCollectionViewModel) throws {
guard !existingTabs.isEmpty else { return }
for existingTab in existingTabs {
guard
let tab = existingTab as? Tab,
let sourceViewModel = WindowControllersManager.shared.windowController(for: tab)?
.mainViewController.tabCollectionViewModel,
let currentIndex = sourceViewModel.tabCollection.tabs.firstIndex(of: tab)
else {
assertionFailure("Failed to find tab collection view model for \(existingTab)")
continue
}
sourceViewModel.moveTab(at: currentIndex, to: targetViewModel, at: targetViewModel.tabs.count)
}
}
func webExtensionController(_ controller: _WKWebExtensionController, openNewTabWith options: _WKWebExtensionTabCreationOptions, for extensionContext: _WKWebExtensionContext) async throws -> (any _WKWebExtensionTab)? {
if let tabCollectionViewModel = WindowControllersManager.shared.lastKeyMainWindowController?.mainViewController.tabCollectionViewModel,
let url = options.desiredURL {
let content = TabContent.contentFromURL(url, source: .ui)
let tab = Tab(content: content,
burnerMode: tabCollectionViewModel.burnerMode)
tabCollectionViewModel.append(tab: tab)
return tab
}
return nil
}
func webExtensionController(_ controller: _WKWebExtensionController, openOptionsPageFor extensionContext: _WKWebExtensionContext) async throws {
assertionFailure("not supported yet")
throw WKWebExtensionControllerDelegateError.notSupported
}
private func webExtensionController(_ controller: _WKWebExtensionController, promptForPermissions permissions: Set<_WKWebExtensionPermission>, in tab: (any _WKWebExtensionTab)?, for extensionContext: _WKWebExtensionContext) async -> (Set<_WKWebExtensionPermission>, Date?) {
return (permissions, nil)
}
func webExtensionController(_ controller: _WKWebExtensionController, promptForPermissionMatchPatterns matchPatterns: Set<_WKWebExtension.MatchPattern>, in tab: (any _WKWebExtensionTab)?, for extensionContext: _WKWebExtensionContext) async -> (Set<_WKWebExtension.MatchPattern>, Date?) {
return (matchPatterns, nil)
}
func webExtensionController(_ controller: _WKWebExtensionController, promptForPermissionToAccess urls: Set<URL>, in tab: (any _WKWebExtensionTab)?, for extensionContext: _WKWebExtensionContext) async -> (Set<URL>, Date?) {
return (urls, nil)
}
func webExtensionController(_ controller: _WKWebExtensionController, presentPopupFor action: _WKWebExtension.Action, for context: _WKWebExtensionContext) async throws {
guard let button = buttonForContext(context) else {
return
}
guard action.presentsPopup,
let popupPopover = action.popupPopover,
let popupWebView = action.popupWebView
else {
return
}
popupWebView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled")
popupPopover.show(relativeTo: button.bounds, of: button, preferredEdge: .maxY)
popupWebView.reload()
}
func webExtensionController(_ controller: _WKWebExtensionController, sendMessage message: Any, to applicationIdentifier: String?, for extensionContext: _WKWebExtensionContext) async throws -> Any? {
try await nativeMessagingHandler.webExtensionController(controller,
sendMessage: message,
to: applicationIdentifier,
for: extensionContext)
}
func webExtensionController(_ controller: _WKWebExtensionController, connectUsingMessagePort port: _WKWebExtension.MessagePort, for extensionContext: _WKWebExtensionContext) async throws {
try await nativeMessagingHandler.webExtensionController(controller,
connectUsingMessagePort: port,
for: extensionContext)
}
}
@available(macOS 14.4, *)
extension WebExtensionManager: WebExtensionInternalSiteHandlerDataSource {
func webExtensionContextForUrl(_ url: URL) -> _WKWebExtensionContext? {
guard let context = contexts.first(where: {
return url.absoluteString.hasPrefix($0.baseURL.absoluteString)
}) else {
assertionFailure("No context for \(url)")
return nil
}
return context
}
}