Repository Public
1import AppKit2import WebKit34/// Services a tab needs from the application, kept as a protocol so tabs can be built in tests.5@MainActor6protocol EngineEnvironment: AnyObject {7 var settings: AppSettings { get }8 var blocker: ContentBlockerService { get }9 var downloads: DownloadManager { get }10 var userScripts: [UserScript] { get }11 /// What a native SP Search page needs (client, history unless private, preferences).12 func searchContext(isPrivate: Bool) -> SearchContext13 /// History, tabs or another synchronized item changed in a regular (non-private) window.14 func browsingDataChanged()15}1617/// Serves the empty placeholder document behind a native SP Search page. Having a real document for18/// `spsearch://results?q=…` makes the results page a genuine entry of the tab's back/forward list.19final class SearchPlaceholderHandler: NSObject, WKURLSchemeHandler {20 func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {21 guard let url = task.request.url else { task.didFailWithError(URLError(.badURL)); return }22 let query = SPSearchURL.parse(url)?.query ?? ""23 let escaped = query.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">")24 let body = Data("<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"color-scheme\" content=\"light dark\"><title>\(escaped)</title></head><body></body></html>".utf8)25 task.didReceive(URLResponse(url: url, mimeType: "text/html", expectedContentLength: body.count, textEncodingName: "utf-8"))26 task.didReceive(body)27 task.didFinish()28 }2930 func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}31}3233/// The window (or test harness) that owns a tab.34@MainActor35protocol TabHost: AnyObject {36 /// Opens a tab for content requested by `tab`. When `configuration` is given (window.open, target=_blank),37 /// the new web view must be created with exactly that configuration.38 func tab(_ tab: BrowserTab, openTabFor url: URL?, configuration: WKWebViewConfiguration?, inBackground: Bool) -> BrowserTab?39 func tabRequestsClose(_ tab: BrowserTab)40 func tabStateDidChange(_ tab: BrowserTab)41 var hostWindow: NSWindow? { get }42}4344/// A pending camera/microphone request shown in the tab until the user answers.45struct PermissionPrompt: Identifiable {46 let id = UUID()47 let host: String48 let permissions: [SitePermission]49 let resolve: @MainActor (_ granted: Bool, _ remember: Bool) -> Void50}5152/// A short, dismissible message attached to a tab (blocked pop-up, blocked navigation…).53struct TabNotice: Identifiable, Equatable {54 enum Action: Equatable { case none, allowPopups(String) }55 let id = UUID()56 var symbol: String57 var text: String58 var action: Action = .none59}6061@MainActor62@Observable63final class BrowserTab: Identifiable {64 let id: UUID65 @ObservationIgnored let profile: ProfileContext66 @ObservationIgnored unowned let environment: EngineEnvironment67 @ObservationIgnored weak var host: TabHost?6869 // Observable page state70 private(set) var url: URL?71 private(set) var title = ""72 private(set) var favicon: NSImage?73 private(set) var isLoading = false74 private(set) var progress = 0.075 private(set) var canGoBack = false76 private(set) var canGoForward = false77 private(set) var security: SecurityState = .none78 private(set) var certificate: CertificateSummary?79 private(set) var warnings: [URLWarning] = []80 /// The link under the pointer, as reported by the page bridge (nil when none).81 private(set) var hovered: HoveredLink?82 var hoveredLink: String? { hovered?.url.absoluteString }83 /// How far the page is scrolled, 0…1 (AURA Focus Trail).84 private(set) var readingProgress = 0.085 /// True when the page is long enough for a progress line to mean something.86 private(set) var isLongPage = false87 var error: PageError?88 var crashed = false89 var notice: TabNotice?90 var permissionPrompt: PermissionPrompt?91 var readerArticle: ReaderArticle?92 private(set) var thumbnail: NSImage?93 private(set) var crashCount = 094 /// The native results model while this tab shows an SP Search page.95 private(set) var searchPage: SearchPageModel?9697 // Organisation98 var isPinned = false99 var groupID: UUID?100 var workspaceID: UUID?101 var lastActive = Date()102 /// The tab this one was opened from (links between tabs in Constellation and Flow).103 var openerID: UUID?104 /// Where, in the opener's page, the link that created this tab was pressed (unit coordinates): the tab morphs out of that point.105 @ObservationIgnored var morphOrigin: CGPoint?106 /// Last link pressed in this tab's page: address and unit position.107 @ObservationIgnored fileprivate(set) var lastPress: (url: URL, point: CGPoint, at: Date)?108 @ObservationIgnored fileprivate var pendingTransition: FlowTransition?109110 // Web view lifecycle111 private(set) var webView: WKWebView?112 @ObservationIgnored private var observations: [NSKeyValueObservation] = []113 @ObservationIgnored private var coordinator: TabCoordinator?114 @ObservationIgnored private var savedInteractionState: Data?115 @ObservationIgnored fileprivate var userInitiatedURL: URL?116 @ObservationIgnored private var restoredTitle = ""117118 var isSuspended: Bool { webView == nil && url != nil }119 var isBlank: Bool { url == nil }120 /// True while the tab shows native SP Search results.121 var isSearchPage: Bool { SPSearchURL.isSearch(url) }122 var searchQuery: String? { SPSearchURL.parse(url)?.query }123 var displayTitle: String {124 if let query = searchQuery { return query }125 if !title.isEmpty { return title }126 if let url { return url.host ?? url.absoluteString }127 return profile.isPrivate ? L("Private Tab") : L("New Tab")128 }129130 init(profile: ProfileContext, environment: EngineEnvironment, id: UUID = UUID()) {131 self.id = id132 self.profile = profile133 self.environment = environment134 }135136 /// Restores a tab from a saved session without loading it: the page is fetched when the tab is first shown.137 convenience init(snapshot: TabSnapshot, profile: ProfileContext, environment: EngineEnvironment) {138 self.init(profile: profile, environment: environment, id: snapshot.id)139 url = snapshot.url.flatMap(URL.init(string:))140 title = snapshot.title141 restoredTitle = snapshot.title142 isPinned = snapshot.isPinned143 groupID = snapshot.groupID144 workspaceID = snapshot.workspaceID145 savedInteractionState = snapshot.interactionState146 openerID = snapshot.openerID147 favicon = FaviconLoader.shared.cached(forHost: url?.host)148 }149150 func snapshot() -> TabSnapshot {151 var state = savedInteractionState152 if let live = webView?.interactionState as? Data { state = live }153 // Very large back/forward states are dropped rather than bloating the session file.154 if let size = state?.count, size > 2_000_000 { state = nil }155 return TabSnapshot(id: id, url: url?.absoluteString, title: title, isPinned: isPinned, groupID: groupID,156 workspaceID: workspaceID, interactionState: state, openerID: openerID)157 }158159 // MARK: Web view lifecycle160161 static func makeConfiguration(profile: ProfileContext, environment: EngineEnvironment) -> WKWebViewConfiguration {162 let configuration = WKWebViewConfiguration()163 configuration.websiteDataStore = profile.dataStore164 configuration.applicationNameForUserAgent = "Version/18.0 Safari/605.1.15 SPBrowser/1.0"165 configuration.upgradeKnownHostsToHTTPS = environment.settings.upgradeToHTTPS166 configuration.preferences.isElementFullscreenEnabled = true167 configuration.preferences.isFraudulentWebsiteWarningEnabled = true168 configuration.preferences.javaScriptCanOpenWindowsAutomatically = false169 configuration.defaultWebpagePreferences.allowsContentJavaScript = true170 configuration.allowsAirPlayForMediaPlayback = true171 configuration.suppressesIncrementalRendering = false172 configuration.setURLSchemeHandler(SearchPlaceholderHandler(), forURLScheme: SPSearchURL.scheme)173 return configuration174 }175176 /// Creates the web view if needed. `configuration` is supplied by WebKit for pages opened by other pages.177 @discardableResult178 func ensureWebView(adopting configuration: WKWebViewConfiguration? = nil) -> WKWebView {179 if let webView { return webView }180 let config = configuration ?? Self.makeConfiguration(profile: profile, environment: environment)181 // A configuration supplied by WebKit (window.open) has no handler yet; without one the tab could not show a search.182 if config.urlSchemeHandler(forURLScheme: SPSearchURL.scheme) == nil {183 config.setURLSchemeHandler(SearchPlaceholderHandler(), forURLScheme: SPSearchURL.scheme)184 }185 environment.blocker.register(config.userContentController)186 AuraPageBridge.shared.install(on: config.userContentController)187 UserScriptInjector.install(environment.userScripts, enabled: environment.settings.userScriptsEnabled && !profile.isPrivate,188 into: config.userContentController)189 let view = WKWebView(frame: NSRect(x: 0, y: 0, width: 1024, height: 768), configuration: config)190 let coordinator = TabCoordinator(tab: self)191 view.navigationDelegate = coordinator192 view.uiDelegate = coordinator193 view.allowsBackForwardNavigationGestures = true194 view.allowsMagnification = true195 view.allowsLinkPreview = true196 let agent = environment.settings.customUserAgent.trimmingCharacters(in: .whitespaces)197 if !agent.isEmpty { view.customUserAgent = agent }198 #if DEBUG199 // Web Inspector is a development aid only; release builds never mark pages inspectable.200 view.isInspectable = true201 #endif202 self.coordinator = coordinator203 webView = view204 AuraPageBridge.shared.attach(self, to: view)205 observe(view)206207 if configuration == nil {208 if let state = savedInteractionState {209 view.interactionState = state210 savedInteractionState = nil211 if view.url == nil, let url { start(url, in: view) }212 } else if let url {213 userInitiatedURL = url214 start(url, in: view)215 }216 }217 return view218 }219220 private func observe(_ view: WKWebView) {221 let sync: @Sendable () -> Void = { [weak self] in Task { @MainActor in self?.syncFromWebView() } }222 observations = [223 view.observe(\.title) { _, _ in sync() },224 view.observe(\.url) { _, _ in sync() },225 view.observe(\.isLoading) { _, _ in sync() },226 view.observe(\.estimatedProgress) { _, _ in sync() },227 view.observe(\.canGoBack) { _, _ in sync() },228 view.observe(\.canGoForward) { _, _ in sync() },229 view.observe(\.hasOnlySecureContent) { _, _ in sync() },230 ]231 }232233 fileprivate func syncFromWebView() {234 guard let view = webView else { return }235 let newURL = view.url236 // After a failed load WebKit reports no URL; the address that failed stays visible so it can be corrected or retried.237 if newURL != url, newURL != nil || (!view.isLoading && error == nil) {238 if newURL?.host != url?.host { favicon = FaviconLoader.shared.cached(forHost: newURL?.host) }239 url = newURL240 warnings = newURL.map(URLInspector.warnings(for:)) ?? []241 }242 let newTitle = view.title ?? ""243 if newTitle != title, !(newTitle.isEmpty && view.isLoading) {244 title = newTitle245 if environment.settings.flowEnabled, !newTitle.isEmpty, !isSearchPage { let tabID = id; profile.flow.update { $0.updateTitle(newTitle, tabID: tabID) } }246 if let url, !profile.isPrivate { profile.history.updateTitle(newTitle, for: url) }247 }248 if isLoading != view.isLoading { isLoading = view.isLoading }249 if abs(progress - view.estimatedProgress) > 0.01 || view.estimatedProgress >= 1 { progress = view.estimatedProgress }250 if canGoBack != view.canGoBack { canGoBack = view.canGoBack }251 if canGoForward != view.canGoForward { canGoForward = view.canGoForward }252 let state: SecurityState = isSearchPage ? .none : SecurityState.evaluate(url: url, hasOnlySecureContent: view.hasOnlySecureContent)253 if state != security { security = state }254 refreshSearchPage()255 host?.tabStateDidChange(self)256 }257258 /// Creates, updates or drops the native search model so that it always matches the tab's address.259 func refreshSearchPage() {260 guard let parsed = SPSearchURL.parse(url) else {261 if searchPage != nil { searchPage = nil }262 return263 }264 let model = searchPage ?? SearchPageModel(context: environment.searchContext(isPrivate: profile.isPrivate))265 if searchPage == nil { searchPage = model }266 model.show(query: parsed.query, kind: parsed.kind)267 if favicon != nil { favicon = nil }268 }269270 /// Runs an SP Search in this tab.271 func search(_ query: String, kind: SearchKind = .web) {272 guard let target = SPSearchURL.make(query: query, kind: kind) else { return }273 load(target)274 }275276 /// Releases the web view of a background tab to free memory. The address, title and back/forward list are kept.277 func suspend() {278 guard let view = webView, !isLoading, url != nil, permissionPrompt == nil else { return }279 savedInteractionState = view.interactionState as? Data280 tearDownWebView()281 }282283 func tearDownWebView() {284 observations.forEach { $0.invalidate() }285 observations = []286 if let view = webView {287 view.stopLoading()288 view.navigationDelegate = nil289 view.uiDelegate = nil290 view.removeFromSuperview()291 }292 permissionPrompt?.resolve(false, false)293 permissionPrompt = nil294 webView = nil295 hovered = nil296 coordinator = nil297 isLoading = false298 progress = 0299 }300301 // MARK: Navigation302303 /// Loads `target`. `userInitiated` marks addresses typed or chosen by the user, which may use schemes304 /// (such as file:) that web content itself is not allowed to navigate to.305 func load(_ target: URL, userInitiated: Bool = true) {306 error = nil307 crashed = false308 readerArticle = nil309 notice = nil310 if userInitiated { userInitiatedURL = target }311 if webView == nil { url = target; savedInteractionState = nil; refreshSearchPage(); ensureWebView(); return }312 url = target313 refreshSearchPage()314 if let webView { start(target, in: webView) }315 }316317 /// Local files must go through `loadFileURL`, which hands the web content process a sandbox grant for that file.318 /// Access is limited to the file itself: the app was only given that file by the user, not its folder.319 private func start(_ target: URL, in view: WKWebView) {320 if target.isFileURL {321 view.loadFileURL(target, allowingReadAccessTo: target)322 } else {323 view.load(URLRequest(url: target))324 }325 }326327 func reload(ignoringCache: Bool = false) {328 crashed = false329 readerArticle = nil330 let view = ensureWebView()331 if let failed = error?.url, error?.kind != .blocked {332 error = nil333 userInitiatedURL = failed334 start(failed, in: view)335 } else if view.url == nil, let url {336 error = nil337 userInitiatedURL = url338 start(url, in: view)339 } else {340 error = nil341 if ignoringCache { view.reloadFromOrigin() } else { view.reload() }342 }343 }344345 /// Returns the tab to the start page, dropping the current page and its web view.346 func showStartPage() {347 tearDownWebView()348 url = nil; title = ""; favicon = nil; error = nil; crashed = false; readerArticle = nil; searchPage = nil349 security = .none; certificate = nil; warnings = []; canGoBack = false; canGoForward = false350 host?.tabStateDidChange(self)351 }352353 func stopLoading() { webView?.stopLoading() }354 func goBack() { error = nil; readerArticle = nil; webView?.goBack() }355 func goForward() { error = nil; readerArticle = nil; webView?.goForward() }356357 var backList: [WKBackForwardListItem] { webView?.backForwardList.backList.reversed() ?? [] }358 var forwardList: [WKBackForwardListItem] { webView?.backForwardList.forwardList ?? [] }359 func go(to item: WKBackForwardListItem) { error = nil; readerArticle = nil; webView?.go(to: item) }360361 // MARK: Page features362363 var zoom: Double { Double(webView?.pageZoom ?? 1) }364365 func setZoom(_ value: Double) {366 let clamped = min(max(value, 0.3), 5.0)367 webView?.pageZoom = clamped368 profile.permissions.setZoom(clamped, host: url?.host)369 }370371 func find(_ text: String, backwards: Bool = false) async -> Bool {372 guard let view = webView, !text.isEmpty else { return false }373 let configuration = WKFindConfiguration()374 configuration.backwards = backwards375 configuration.wraps = true376 configuration.caseSensitive = false377 return (try? await view.find(text, configuration: configuration).matchFound) ?? false378 }379380 func evaluate<T>(_ script: String, as type: T.Type = T.self) async -> T? {381 guard let view = webView else { return nil }382 return try? await view.evaluateJavaScript(script, in: nil, contentWorld: PageScripts.world) as? T383 }384385 func pageText() async -> String { await evaluate(PageScripts.pageText, as: String.self) ?? "" }386 func pageSource() async -> String { await evaluate(PageScripts.pageSource, as: String.self) ?? "" }387388 func pageMetadata() async -> PageMetadata? {389 guard let json = await evaluate(PageScripts.metadata, as: String.self) else { return nil }390 return try? JSONDecoder().decode(PageMetadata.self, from: Data(json.utf8))391 }392393 /// Toggles the reader view. Returns false when the page has no readable article.394 @discardableResult395 func toggleReader() async -> Bool {396 if readerArticle != nil { readerArticle = nil; return true }397 guard let json = await evaluate(PageScripts.reader, as: String.self),398 let article = try? JSONDecoder().decode(ReaderArticle.self, from: Data(json.utf8)), article.isReadable else { return false }399 readerArticle = article400 return true401 }402403 func captureThumbnail() {404 guard let view = webView, view.window != nil, view.bounds.width > 10 else { return }405 let configuration = WKSnapshotConfiguration()406 configuration.snapshotWidth = 320407 view.takeSnapshot(with: configuration) { [weak self] image, _ in408 Task { @MainActor in if let image { self?.thumbnail = image } }409 }410 }411412 func setMuted(_ muted: Bool) async {413 await webView?.setCameraCaptureState(muted ? .muted : .active)414 await webView?.setMicrophoneCaptureState(muted ? .muted : .active)415 }416417 // MARK: Events from the coordinator418419 fileprivate func didCommit() {420 guard let view = webView else { return }421 error = nil422 crashed = false423 readerArticle = nil424 certificate = CertificateSummary(trust: view.serverTrust)425 syncFromWebView()426 if let zoom = profile.permissions.zoom(forHost: url?.host) { view.pageZoom = zoom } else if view.pageZoom != 1 { view.pageZoom = 1 }427 if let url, !profile.isPrivate, profile.history.record(url: url, title: view.title ?? restoredTitle) { environment.browsingDataChanged() }428 recordFlowStep()429 hovered = nil430 readingProgress = 0431 isLongPage = false432 restoredTitle = ""433 }434435 fileprivate func didFinish() {436 syncFromWebView()437 guard let pageURL = url, let host = pageURL.host, pageURL.scheme?.hasPrefix("http") == true else { return }438 Task { [weak self] in439 guard let self, let iconString = await self.evaluate(PageScripts.faviconURL, as: String.self),440 let iconURL = URL(string: iconString) else { return }441 if let image = await FaviconLoader.shared.load(from: iconURL, host: host), self.url?.host == host {442 self.favicon = image443 }444 }445 }446447 fileprivate func didFail(_ failure: Error, url failedURL: URL?) {448 guard !PageError.isBenign(failure) else { return }449 error = PageError(error: failure, url: failedURL ?? url)450 if let failedURL { url = failedURL }451 isLoading = false452 Log.event("navigation", "failed \(Log.redact(failedURL)) code=\((failure as NSError).code)")453 host?.tabStateDidChange(self)454 }455456 func processTerminated() {457 crashCount += 1458 crashed = true459 isLoading = false460 Log.event("navigation", "web content process terminated for \(Log.redact(url))")461 host?.tabStateDidChange(self)462 }463464 fileprivate func consumeUserInitiated(_ candidate: URL?) -> Bool {465 guard let expected = userInitiatedURL, let candidate else { return false }466 // Search pages differ only by their query, so they must match exactly; web addresses may be normalised by WebKit.467 let matches = expected == candidate || expected.absoluteString == candidate.absoluteString468 || (!SPSearchURL.isSearch(expected) && expected.host == candidate.host && expected.path == candidate.path)469 if matches { userInitiatedURL = nil }470 return matches471 }472473 // MARK: AURA page bridge474475 /// A message from the page bridge. Only main-frame messages of this tab's own web view reach here.476 func handleBridgeMessage(_ body: [String: Any]) {477 switch body["t"] as? String {478 case "hover":479 let link = HoveredLink.parse(body)480 if link != hovered { hovered = link }481 case "press":482 if let link = HoveredLink.parse(body) { lastPress = (link.url, CGPoint(x: link.unitRect.minX, y: link.unitRect.minY), Date()) }483 case "scroll":484 let p = min(max((body["p"] as? NSNumber)?.doubleValue ?? 0, 0), 1)485 if abs(p - readingProgress) > 0.003 || p == 0 || p == 1 { readingProgress = p }486 let tall = (body["tall"] as? Bool) ?? false487 if tall != isLongPage { isLongPage = tall }488 default: break489 }490 }491492 /// The unit point of the link that was pressed in this tab within the last second and a half, if it matches `url`.493 func recentPressPoint(for url: URL?) -> CGPoint? {494 guard let press = lastPress, Date().timeIntervalSince(press.at) < 1.5 else { return nil }495 if let url, url != press.url, url.host != press.url.host { return nil }496 return press.point497 }498499 /// AURA Flow: remembers how this page was reached. A private context keeps its trail in memory only.500 private func recordFlowStep() {501 let transition = pendingTransition502 pendingTransition = nil503 guard environment.settings.flowEnabled, let url, HistoryStore.isRecordable(url) || isSearchPage else { return }504 let tabID = id, opener = openerID, text = url.absoluteString, pageTitle = searchQuery ?? title505 profile.flow.update { trail in506 let effective: FlowTransition507 if trail.cursor[tabID] == nil, let opener, trail.cursor[opener] != nil, transition != .typed { effective = .opened(from: opener) }508 else { effective = transition ?? .link }509 trail.record(url: text, title: pageTitle, tabID: tabID, transition: effective)510 }511 }512}513514/// WebKit delegate for one tab. It holds the tab weakly, so a closed tab never outlives its web view callbacks.515@MainActor516final class TabCoordinator: NSObject, WKNavigationDelegate, WKUIDelegate {517 private weak var tab: BrowserTab?518519 init(tab: BrowserTab) { self.tab = tab }520521 // MARK: Navigation policy522523 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,524 preferences: WKWebpagePreferences) async -> (WKNavigationActionPolicy, WKWebpagePreferences) {525 guard let tab, let url = navigationAction.request.url else { return (.cancel, preferences) }526 let isMainFrame = navigationAction.targetFrame?.isMainFrame ?? true527 let typed = isMainFrame && tab.consumeUserInitiated(url)528 if isMainFrame {529 switch navigationAction.navigationType {530 case .backForward, .reload: tab.pendingTransition = .revisit531 default: tab.pendingTransition = typed ? .typed : .link532 }533 }534 let sourceIsFile = navigationAction.sourceFrame.request.url?.isFileURL ?? false535 let settings = tab.environment.settings536537 // Saving generated content (a "download" link to a data: or blob: URL) is not a navigation: nothing is displayed.538 if navigationAction.shouldPerformDownload, ["data", "blob", "http", "https"].contains(url.scheme?.lowercased() ?? "") {539 return (.download, preferences)540 }541542 // Native search pages are opened by the user (address bar, results page, back/forward), never by web content.543 if SPSearchURL.isSearch(url) {544 let fromSearchPage = SPSearchURL.isSearch(navigationAction.sourceFrame.request.url) || SPSearchURL.isSearch(webView.url)545 // `tab.url == url`: the tab itself asked for this page (address bar, results page, restored session).546 let allowed = isMainFrame && (typed || tab.url == url || fromSearchPage || navigationAction.navigationType == .backForward || navigationAction.navigationType == .reload)547 return (allowed ? .allow : .cancel, preferences)548 }549550 switch URLSafety.verdict(for: url, isMainFrame: isMainFrame, typedByUser: typed, sourceIsFile: sourceIsFile) {551 case .block(let reason):552 Log.event("policy", "blocked \(url.scheme ?? "?"): \(reason)")553 if isMainFrame {554 tab.notice = TabNotice(symbol: "hand.raised", text: L("A navigation to a “%@:” address was blocked.", url.scheme ?? ""))555 }556 return (.cancel, preferences)557 case .external:558 await confirmExternal(url, from: tab)559 return (.cancel, preferences)560 case .allow:561 break562 }563564 if isMainFrame, navigationAction.navigationType == .linkActivated, settings.warnOnDeceptiveURLs {565 let deceptive = URLInspector.warnings(for: url).filter(\.isDeceptive)566 if let first = deceptive.first, await !confirm(title: L("This link may be misleading"),567 message: first.message + "\n\n" + L("Real destination: %@", url.host ?? url.absoluteString),568 confirm: L("Open Anyway"), in: tab) {569 return (.cancel, preferences)570 }571 }572573 if navigationAction.navigationType == .linkActivated, navigationAction.modifierFlags.contains(.command), isMainFrame {574 _ = tab.host?.tab(tab, openTabFor: url, configuration: nil, inBackground: !navigationAction.modifierFlags.contains(.shift))575 return (.cancel, preferences)576 }577578 if isMainFrame {579 let host = url.host580 preferences.allowsContentJavaScript = tab.profile.permissions.decision(.javascript, host: host) != .deny581 let popups = tab.profile.permissions.decision(.popups, host: host)582 webView.configuration.preferences.javaScriptCanOpenWindowsAutomatically = (popups == .allow) || !settings.blockPopups583 }584 return (.allow, preferences)585 }586587 func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse) async -> WKNavigationResponsePolicy {588 if let http = navigationResponse.response as? HTTPURLResponse,589 let disposition = http.value(forHTTPHeaderField: "Content-Disposition"),590 disposition.lowercased().hasPrefix("attachment") {591 return .download592 }593 return navigationResponse.canShowMIMEType ? .allow : .download594 }595596 func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {597 tab?.environment.downloads.adopt(download, from: webView, isPrivate: tab?.profile.isPrivate ?? false)598 }599600 func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {601 tab?.environment.downloads.adopt(download, from: webView, isPrivate: tab?.profile.isPrivate ?? false)602 }603604 // MARK: Navigation progress605606 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {607 tab?.error = nil608 tab?.syncFromWebView()609 }610611 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { tab?.didCommit() }612 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { tab?.didFinish() }613614 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {615 tab?.didFail(error, url: (error as NSError).userInfo[NSURLErrorFailingURLErrorKey] as? URL)616 }617618 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {619 tab?.didFail(error, url: nil)620 }621622 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { tab?.processTerminated() }623624 /// TLS validation is always left to the system. Only HTTP authentication is answered here, by asking the user.625 func webView(_ webView: WKWebView, respondTo challenge: URLAuthenticationChallenge) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {626 let method = challenge.protectionSpace.authenticationMethod627 guard [NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM].contains(method),628 challenge.previousFailureCount < 3, let tab, let window = tab.host?.hostWindow else {629 return (.performDefaultHandling, nil)630 }631 let space = challenge.protectionSpace632 let alert = NSAlert()633 alert.messageText = L("Sign in to %@", space.host)634 alert.informativeText = space.receivesCredentialSecurely635 ? L("The site asks for a user name and password.")636 : L("The site asks for a user name and password. They will be sent without encryption.")637 let user = NSTextField(frame: NSRect(x: 0, y: 28, width: 260, height: 22))638 user.placeholderString = L("User name")639 let password = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 22))640 password.placeholderString = L("Password")641 let stack = NSView(frame: NSRect(x: 0, y: 0, width: 260, height: 50))642 stack.addSubview(user); stack.addSubview(password)643 alert.accessoryView = stack644 alert.addButton(withTitle: L("Sign In"))645 alert.addButton(withTitle: L("Cancel"))646 alert.window.initialFirstResponder = user647 guard await alert.beginSheetModal(for: window) == .alertFirstButtonReturn else { return (.cancelAuthenticationChallenge, nil) }648 return (.useCredential, URLCredential(user: user.stringValue, password: password.stringValue, persistence: .forSession))649 }650651 // MARK: Windows opened by pages652653 func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction,654 windowFeatures: WKWindowFeatures) -> WKWebView? {655 guard let tab else { return nil }656 if let url = navigationAction.request.url, !url.absoluteString.isEmpty,657 case .block = URLSafety.verdict(for: url, isMainFrame: true, typedByUser: false) { return nil }658 let opened = tab.host?.tab(tab, openTabFor: navigationAction.request.url, configuration: configuration, inBackground: false)659 return opened?.webView660 }661662 func webViewDidClose(_ webView: WKWebView) {663 guard let tab else { return }664 tab.host?.tabRequestsClose(tab)665 }666667 // MARK: JavaScript dialogs668669 private func originTitle(_ frame: WKFrameInfo) -> String {670 let host = frame.securityOrigin.host671 return host.isEmpty ? L("This page says:") : L("%@ says:", host)672 }673674 func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async {675 guard let window = tab?.host?.hostWindow else { return }676 let alert = NSAlert()677 alert.messageText = originTitle(frame)678 alert.informativeText = String(message.prefix(2000))679 alert.addButton(withTitle: L("OK"))680 _ = await alert.beginSheetModal(for: window)681 }682683 func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async -> Bool {684 guard let tab else { return false }685 return await confirm(title: originTitle(frame), message: String(message.prefix(2000)), confirm: L("OK"), in: tab)686 }687688 func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?,689 initiatedByFrame frame: WKFrameInfo) async -> String? {690 guard let window = tab?.host?.hostWindow else { return nil }691 let alert = NSAlert()692 alert.messageText = originTitle(frame)693 alert.informativeText = String(prompt.prefix(2000))694 let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 280, height: 22))695 field.stringValue = defaultText ?? ""696 alert.accessoryView = field697 alert.addButton(withTitle: L("OK"))698 alert.addButton(withTitle: L("Cancel"))699 alert.window.initialFirstResponder = field700 return await alert.beginSheetModal(for: window) == .alertFirstButtonReturn ? field.stringValue : nil701 }702703 func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters, initiatedByFrame frame: WKFrameInfo) async -> [URL]? {704 guard let window = tab?.host?.hostWindow else { return nil }705 let panel = NSOpenPanel()706 panel.allowsMultipleSelection = parameters.allowsMultipleSelection707 panel.canChooseDirectories = parameters.allowsDirectories708 panel.canChooseFiles = true709 panel.message = L("Choose the file to send to %@", frame.securityOrigin.host)710 return await panel.beginSheetModal(for: window) == .OK ? panel.urls : nil711 }712713 // MARK: Permissions714715 /// Camera and microphone: a stored decision is applied silently; otherwise the user is asked in the tab.716 /// macOS additionally asks once for the application itself.717 func webView(_ webView: WKWebView, decideMediaCapturePermissionsFor origin: WKSecurityOrigin, initiatedBy frame: WKFrameInfo,718 type: WKMediaCaptureType) async -> WKPermissionDecision {719 guard let tab else { return .deny }720 // The decision belongs to the page the user is looking at, not to an embedded third-party frame.721 guard frame.isMainFrame || origin.host == webView.url?.host else { return .deny }722 let needed: [SitePermission]723 switch type {724 case .camera: needed = [.camera]725 case .microphone: needed = [.microphone]726 case .cameraAndMicrophone: needed = [.camera, .microphone]727 @unknown default: return .deny728 }729 let host = origin.host730 let store = tab.profile.permissions731 let decisions = needed.map { store.decision($0, host: host) }732 if decisions.contains(.deny) { return .deny }733 if decisions.allSatisfy({ $0 == .allow }) { return .grant }734 if tab.permissionPrompt != nil { return .deny }735 return await withCheckedContinuation { continuation in736 tab.permissionPrompt = PermissionPrompt(host: host, permissions: needed) { [weak tab] granted, remember in737 tab?.permissionPrompt = nil738 if remember { needed.forEach { store.set(granted ? .allow : .deny, for: $0, host: host) } }739 continuation.resume(returning: granted ? .grant : .deny)740 }741 }742 }743744 // MARK: Helpers745746 private func confirm(title: String, message: String, confirm: String, in tab: BrowserTab) async -> Bool {747 guard let window = tab.host?.hostWindow else { return false }748 let alert = NSAlert()749 alert.messageText = title750 alert.informativeText = message751 alert.addButton(withTitle: confirm)752 alert.addButton(withTitle: L("Cancel"))753 return await alert.beginSheetModal(for: window) == .alertFirstButtonReturn754 }755756 /// Links to other applications never open silently: the user sees which application and confirms.757 private func confirmExternal(_ url: URL, from tab: BrowserTab) async {758 guard let handler = NSWorkspace.shared.urlForApplication(toOpen: url) else {759 tab.notice = TabNotice(symbol: "questionmark.app", text: L("No application can open “%@:” links.", url.scheme ?? ""))760 return761 }762 let name = FileManager.default.displayName(atPath: handler.path)763 if await confirm(title: L("Open this link in %@?", name),764 message: L("The page wants to open a “%@:” link outside SP Browser.", url.scheme ?? ""),765 confirm: L("Open"), in: tab) {766 NSWorkspace.shared.open(url)767 }768 }769}770771/// Receives the messages of the browser's own page script (isolated world) and hands them to the tab that owns the web view.772/// One instance serves every web view: a page opened with `window.open` shares its opener's content controller.773@MainActor774final class AuraPageBridge: NSObject, WKScriptMessageHandler {775 static let shared = AuraPageBridge()776 private let tabs = NSMapTable<WKWebView, BrowserTab>.weakToWeakObjects()777 private let installed = NSHashTable<WKUserContentController>.weakObjects()778779 static var userScript: WKUserScript {780 WKUserScript(source: ReadingScripts.bridge, injectionTime: .atDocumentStart, forMainFrameOnly: true, in: PageScripts.world)781 }782783 func install(on controller: WKUserContentController) {784 guard !installed.contains(controller) else { return }785 installed.add(controller)786 controller.add(self, contentWorld: PageScripts.world, name: ReadingScripts.bridgeName)787 if !controller.userScripts.contains(where: { $0.source == ReadingScripts.bridge }) { controller.addUserScript(Self.userScript) }788 }789790 func attach(_ tab: BrowserTab, to webView: WKWebView) { tabs.setObject(tab, forKey: webView) }791792 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {793 guard message.frameInfo.isMainFrame, let webView = message.webView, let body = message.body as? [String: Any] else { return }794 tabs.object(forKey: webView)?.handleBridgeMessage(body)795 }796}797