Repository Public
1import SwiftUI2import UIKit3import WebKit45/// Serves the empty placeholder document behind a native SP Search page, so that `spsearch://results?q=…`6/// is a real entry of the tab's back/forward list (same approach as the Mac app).7final class MobileSearchPlaceholderHandler: NSObject, WKURLSchemeHandler {8 func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {9 guard let url = task.request.url else { task.didFailWithError(URLError(.badURL)); return }10 let query = SPSearchURL.parse(url)?.query ?? ""11 let escaped = query.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">")12 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)13 task.didReceive(URLResponse(url: url, mimeType: "text/html", expectedContentLength: body.count, textEncodingName: "utf-8"))14 task.didReceive(body)15 task.didFinish()16 }1718 func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}19}2021/// Why a page could not be shown.22struct PageFailure: Equatable {23 var title: String24 var message: String25 var url: URL?26 var isOffline: Bool2728 init(error: Error, url: URL?) {29 let ns = error as NSError30 self.url = url31 isOffline = ns.domain == NSURLErrorDomain && [NSURLErrorNotConnectedToInternet, NSURLErrorNetworkConnectionLost, NSURLErrorDataNotAllowed].contains(ns.code)32 switch (ns.domain, ns.code) {33 case (NSURLErrorDomain, NSURLErrorNotConnectedToInternet), (NSURLErrorDomain, NSURLErrorDataNotAllowed):34 title = L("You are offline"); message = L("Check the internet connection, then try again.")35 case (NSURLErrorDomain, NSURLErrorCannotFindHost), (NSURLErrorDomain, NSURLErrorDNSLookupFailed):36 title = L("The site cannot be found"); message = L("Check the address for typing mistakes.")37 case (NSURLErrorDomain, NSURLErrorTimedOut):38 title = L("The site took too long to answer"); message = L("It may be busy or unreachable. Try again in a moment.")39 case (NSURLErrorDomain, NSURLErrorServerCertificateUntrusted), (NSURLErrorDomain, NSURLErrorServerCertificateHasBadDate),40 (NSURLErrorDomain, NSURLErrorServerCertificateHasUnknownRoot), (NSURLErrorDomain, NSURLErrorSecureConnectionFailed):41 title = L("The connection is not private"); message = L("The site's security certificate could not be verified. SP Browser did not open the page.")42 default:43 title = L("The page could not be opened"); message = ns.localizedDescription44 }45 }4647 /// Cancellations and "frame load interrupted" (a download took over) are not failures to show.48 static func isBenign(_ error: Error) -> Bool {49 let ns = error as NSError50 return (ns.domain == NSURLErrorDomain && ns.code == NSURLErrorCancelled) || (ns.domain == "WebKitErrorDomain" && (ns.code == 102 || ns.code == 204))51 }52}5354/// One browser tab on iPhone or iPad. It owns its `WKWebView` once loaded; restored tabs load when first shown.55@MainActor56@Observable57final class MobileTab: Identifiable {58 let id: UUID59 let isPrivate: Bool60 @ObservationIgnored unowned let model: BrowserModel6162 private(set) var url: URL?63 private(set) var title = ""64 private(set) var isLoading = false65 private(set) var progress = 0.066 private(set) var canGoBack = false67 private(set) var canGoForward = false68 private(set) var isSecure = false69 var failure: PageFailure?70 private(set) var thumbnail: UIImage?71 /// The native results model while the tab shows an SP Search page.72 private(set) var searchPage: SearchPageModel?73 var lastActive = Date()74 /// The tab this one was opened from (AURA Constellation and Flow), when known.75 var openerID: UUID?76 /// How far the page is scrolled, 0…1 (Focus Trail, compact bar).77 private(set) var readingProgress = 0.078 /// True when the page is at least one and a half screens tall.79 private(set) var isLongPage = false80 /// Where the user's finger last took the page. The chrome contracts on `.down` and comes back on `.up` or at the top.81 enum ScrollDirection: Sendable { case idle, down, up }82 private(set) var scrollDirection: ScrollDirection = .idle83 private(set) var isAtTop = true84 /// The article shown by the reader, when it is on.85 var readerArticle: ReaderArticle?8687 private(set) var webView: WKWebView?88 @ObservationIgnored private var observations: [NSKeyValueObservation] = []89 @ObservationIgnored private var coordinator: MobileTabCoordinator?90 @ObservationIgnored private var savedInteractionState: Data?91 @ObservationIgnored fileprivate var userInitiatedURL: URL?92 /// A load the app started on behalf of a link (Peek, "open in new tab"): Flow records it as a link, not as a typed address.93 @ObservationIgnored private var linkLoadURL: URL?94 @ObservationIgnored fileprivate var pendingTransition: FlowTransition?95 @ObservationIgnored private var lastOffsetY: CGFloat = 096 @ObservationIgnored private var scrollTravel: CGFloat = 097 @ObservationIgnored private var bottomInset: CGFloat = 09899 /// The browser's own scripts run in this isolated world: pages cannot see or alter them.100 static let internalWorld = WKContentWorld.world(name: "SPBrowserInternal")101102 init(model: BrowserModel, isPrivate: Bool, id: UUID = UUID()) {103 self.model = model104 self.isPrivate = isPrivate105 self.id = id106 }107108 convenience init(snapshot: TabSnapshot, model: BrowserModel) {109 self.init(model: model, isPrivate: false, id: snapshot.id)110 url = snapshot.url.flatMap(URL.init(string:))111 title = snapshot.title112 savedInteractionState = snapshot.interactionState113 openerID = snapshot.openerID114 }115116 func snapshot() -> TabSnapshot {117 var state = savedInteractionState118 if let live = webView?.interactionState as? Data { state = live }119 if let size = state?.count, size > 2_000_000 { state = nil }120 return TabSnapshot(id: id, url: url?.absoluteString, title: title, interactionState: state, openerID: openerID)121 }122123 var isBlank: Bool { url == nil }124 var isSearchPage: Bool { SPSearchURL.isSearch(url) }125 var searchQuery: String? { SPSearchURL.parse(url)?.query }126 var displayTitle: String {127 if let query = searchQuery { return query }128 if !title.isEmpty { return title }129 if let url { return url.host ?? url.absoluteString }130 return isPrivate ? L("Private Tab") : L("New Tab")131 }132 /// Short text for the collapsed address bar: the query, or the site name.133 var addressText: String {134 if let query = searchQuery { return query }135 guard let url else { return "" }136 if let host = url.host { return host.hasPrefix("www.") ? String(host.dropFirst(4)) : host }137 return url.absoluteString138 }139140 private var environment: MobileEnvironment { model.environment }141 private var history: HistoryStore { isPrivate ? model.privateHistory : environment.history }142 /// Private tabs write their path to an in-memory store that dies with the private session.143 private var flow: FlowStore { isPrivate ? model.privateFlow : environment.flow }144 /// True while a web document (not the start page, a native search page or an error) is on screen.145 var showsWebPage: Bool { url != nil && !isSearchPage && failure == nil }146 /// The floating bar may contract: the user is scrolling down a web page that is tall enough to scroll.147 var prefersCompactChrome: Bool { showsWebPage && readerArticle == nil && scrollDirection == .down && !isAtTop }148149 // MARK: Web view150151 @discardableResult152 func ensureWebView(adopting configuration: WKWebViewConfiguration? = nil) -> WKWebView {153 if let webView { return webView }154 let config = configuration ?? {155 let c = WKWebViewConfiguration()156 c.websiteDataStore = isPrivate ? model.privateDataStore : environment.dataStore157 c.applicationNameForUserAgent = "Version/18.0 Mobile/15E148 Safari/604.1 SPBrowser/2.0"158 c.upgradeKnownHostsToHTTPS = environment.settings.upgradeToHTTPS159 c.allowsInlineMediaPlayback = true160 c.allowsAirPlayForMediaPlayback = true161 c.allowsPictureInPictureMediaPlayback = true162 c.preferences.isFraudulentWebsiteWarningEnabled = true163 c.preferences.javaScriptCanOpenWindowsAutomatically = false164 c.preferences.isElementFullscreenEnabled = true165 return c166 }()167 if config.urlSchemeHandler(forURLScheme: SPSearchURL.scheme) == nil {168 config.setURLSchemeHandler(MobileSearchPlaceholderHandler(), forURLScheme: SPSearchURL.scheme)169 }170 let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 390, height: 700), configuration: config)171 let coordinator = MobileTabCoordinator(tab: self)172 view.navigationDelegate = coordinator173 view.uiDelegate = coordinator174 view.allowsBackForwardNavigationGestures = true175 view.allowsLinkPreview = true176 view.isFindInteractionEnabled = true177 view.scrollView.contentInsetAdjustmentBehavior = .never178 view.scrollView.contentInset.bottom = bottomInset179 view.scrollView.verticalScrollIndicatorInsets.bottom = bottomInset180 let refresh = UIRefreshControl()181 refresh.addTarget(coordinator, action: #selector(MobileTabCoordinator.pulledToRefresh(_:)), for: .valueChanged)182 view.scrollView.refreshControl = refresh183 #if DEBUG184 view.isInspectable = true185 #endif186 self.coordinator = coordinator187 webView = view188 observe(view)189 if configuration == nil {190 if let state = savedInteractionState {191 view.interactionState = state192 savedInteractionState = nil193 if view.url == nil, let url { start(url, in: view) }194 } else if let url {195 userInitiatedURL = url196 start(url, in: view)197 }198 }199 return view200 }201202 private func observe(_ view: WKWebView) {203 let sync: @Sendable () -> Void = { [weak self] in Task { @MainActor in self?.syncFromWebView() } }204 observations = [205 view.observe(\.title) { _, _ in sync() }, view.observe(\.url) { _, _ in sync() },206 view.observe(\.isLoading) { _, _ in sync() }, view.observe(\.estimatedProgress) { _, _ in sync() },207 view.observe(\.canGoBack) { _, _ in sync() }, view.observe(\.canGoForward) { _, _ in sync() },208 view.observe(\.hasOnlySecureContent) { _, _ in sync() },209 // Scroll events arrive on the main thread, once per frame: handled at once so the chrome follows the finger.210 view.scrollView.observe(\.contentOffset) { [weak self] _, _ in MainActor.assumeIsolated { self?.scrollChanged() } },211 view.scrollView.observe(\.contentSize) { [weak self] _, _ in MainActor.assumeIsolated { self?.scrollChanged() } },212 ]213 }214215 private func scrollChanged() {216 guard let scroll = webView?.scrollView else { return }217 let inset = scroll.adjustedContentInset218 let y = scroll.contentOffset.y + inset.top219 let visible = scroll.bounds.height - inset.top - inset.bottom220 let travel = scroll.contentSize.height - visible221 let progress = travel > 1 ? Double(min(max(y / travel, 0), 1)) : 0222 if abs(progress - readingProgress) > 0.004 || ((progress == 0 || progress == 1) && progress != readingProgress) { readingProgress = progress }223 let long = visible > 1 && scroll.contentSize.height > visible * 1.5224 if long != isLongPage { isLongPage = long }225 let top = y <= 8226 if top != isAtTop { isAtTop = top }227 let delta = y - lastOffsetY228 lastOffsetY = y229 // Only the user's own scrolling moves the chrome; layout changes and scripted scrolls do not.230 guard scroll.isTracking || scroll.isDecelerating, travel > 80 else { return }231 if top { scrollTravel = 0; if scrollDirection != .idle { scrollDirection = .idle }; return }232 // Rubber-banding at the end of the page is not a change of direction.233 if y >= travel - 1 { return }234 // WebKit reports some offsets twice: a repeat is not a change of direction.235 guard delta != 0 else { return }236 if (delta > 0) != (scrollTravel > 0) { scrollTravel = 0 }237 scrollTravel += delta238 if scrollTravel > 28 { if scrollDirection != .down { scrollDirection = .down } }239 else if scrollTravel < -18 { if scrollDirection != .up { scrollDirection = .up } }240 }241242 /// Screenshot scripts only (`-SPBShow compact`): puts the page and the chrome in the state a downward scroll leaves them in.243 func simulateScrollDown(by distance: CGFloat) {244 guard let scroll = webView?.scrollView else { return }245 scroll.setContentOffset(CGPoint(x: 0, y: min(distance, max(scroll.contentSize.height - scroll.bounds.height, 0))), animated: false)246 scrollDirection = .down247 }248249 /// The user asked for the full bar (tap on the compact pill).250 func expandChrome() {251 scrollTravel = 0252 if scrollDirection != .idle { scrollDirection = .idle }253 }254255 /// Room kept free at the bottom of the page for the floating bar (iPhone).256 func setBottomInset(_ value: CGFloat) {257 bottomInset = value258 guard let scroll = webView?.scrollView, abs(scroll.contentInset.bottom - value) > 0.5 else { return }259 scroll.contentInset.bottom = value260 scroll.verticalScrollIndicatorInsets.bottom = value261 }262263 fileprivate func syncFromWebView() {264 guard let view = webView else { return }265 let newURL = view.url266 if newURL != url, newURL != nil || (!view.isLoading && failure == nil) { url = newURL }267 let newTitle = view.title ?? ""268 if newTitle != title, !(newTitle.isEmpty && view.isLoading) {269 title = newTitle270 if let url, HistoryStore.isRecordable(url) { history.updateTitle(newTitle, for: url) }271 let tabID = id272 if !newTitle.isEmpty, !isSearchPage, let node = flow.trail.node(flow.trail.cursor[tabID]), node.title != newTitle {273 flow.update { $0.updateTitle(newTitle, tabID: tabID) }274 model.flowDidChange()275 }276 }277 if isLoading != view.isLoading {278 isLoading = view.isLoading279 if !view.isLoading { view.scrollView.refreshControl?.endRefreshing() }280 }281 if abs(progress - view.estimatedProgress) > 0.01 || view.estimatedProgress >= 1 { progress = view.estimatedProgress }282 if canGoBack != view.canGoBack { canGoBack = view.canGoBack }283 if canGoForward != view.canGoForward { canGoForward = view.canGoForward }284 let secure = url?.scheme?.lowercased() == "https" && view.hasOnlySecureContent285 if secure != isSecure { isSecure = secure }286 refreshSearchPage()287 model.tabStateDidChange(self)288 }289290 /// Creates, updates or drops the native search model so that it always matches the address.291 func refreshSearchPage() {292 guard let parsed = SPSearchURL.parse(url) else {293 if searchPage != nil { searchPage = nil }294 return295 }296 let page = searchPage ?? SearchPageModel(context: environment.services.searchContext(isPrivate: isPrivate))297 if searchPage == nil { searchPage = page }298 page.show(query: parsed.query, kind: parsed.kind)299 }300301 func tearDownWebView() {302 observations.forEach { $0.invalidate() }303 observations = []304 if let view = webView {305 view.stopLoading()306 view.navigationDelegate = nil307 view.uiDelegate = nil308 view.removeFromSuperview()309 }310 webView = nil311 coordinator = nil312 isLoading = false313 progress = 0314 }315316 /// Frees the web view of a background tab; the address and back/forward list are kept.317 func suspend() {318 guard let view = webView, !isLoading, url != nil else { return }319 savedInteractionState = view.interactionState as? Data320 tearDownWebView()321 }322323 // MARK: Navigation324325 /// - Parameter userInitiated: false when the app follows a link for the user (Peek, a tab opened from another):326 /// Flow then records a link step rather than the start of a new journey.327 func load(_ target: URL, userInitiated: Bool = true) {328 failure = nil329 readerArticle = nil330 userInitiatedURL = target331 linkLoadURL = userInitiated ? nil : target332 if webView == nil { url = target; savedInteractionState = nil; refreshSearchPage(); ensureWebView(); return }333 url = target334 refreshSearchPage()335 if let webView { start(target, in: webView) }336 }337338 private func start(_ target: URL, in view: WKWebView) {339 if target.isFileURL { view.loadFileURL(target, allowingReadAccessTo: target) } else { view.load(URLRequest(url: target)) }340 }341342 func search(_ query: String, kind: SearchKind = .web) {343 guard let target = SPSearchURL.make(query: query, kind: kind) else { return }344 load(target)345 }346347 func reload() {348 readerArticle = nil349 if isSearchPage { searchPage?.reload(ignoringCache: true); return }350 let view = ensureWebView()351 if let failed = failure?.url { failure = nil; userInitiatedURL = failed; start(failed, in: view) }352 else if view.url == nil, let url { failure = nil; userInitiatedURL = url; start(url, in: view) }353 else { failure = nil; view.reload() }354 }355356 func stopLoading() { webView?.stopLoading() }357 func goBack() { failure = nil; readerArticle = nil; webView?.goBack() }358 func goForward() { failure = nil; readerArticle = nil; webView?.goForward() }359360 func showStartPage() {361 tearDownWebView()362 url = nil; title = ""; failure = nil; searchPage = nil; canGoBack = false; canGoForward = false; isSecure = false363 readerArticle = nil; resetReading()364 model.tabStateDidChange(self)365 }366367 func findInPage() { webView?.findInteraction?.presentFindNavigator(showingReplace: false) }368369 func captureThumbnail() {370 guard let view = webView, view.window != nil, view.bounds.width > 10, !isSearchPage else { return }371 let configuration = WKSnapshotConfiguration()372 configuration.snapshotWidth = 360373 view.takeSnapshot(with: configuration) { [weak self] image, _ in374 Task { @MainActor in if let image { self?.thumbnail = image } }375 }376 }377378 // MARK: Reading379380 /// Toggles the reader view. Returns false when the page has no readable article.381 @discardableResult382 func toggleReader() async -> Bool {383 if readerArticle != nil { readerArticle = nil; return true }384 guard showsWebPage, let view = webView,385 let json = try? await view.evaluateJavaScript(ReadingScripts.reader, in: nil, contentWorld: Self.internalWorld) as? String,386 let article = try? JSONDecoder().decode(ReaderArticle.self, from: Data(json.utf8)), article.isReadable else { return false }387 readerArticle = article388 return true389 }390391 /// PNG of the visible page. Only ever called from an explicit user command.392 func capturePNG() async -> Data? {393 guard let view = webView, view.window != nil, showsWebPage else { return nil }394 return await withCheckedContinuation { continuation in395 view.takeSnapshot(with: nil) { image, _ in continuation.resume(returning: image?.pngData()) }396 }397 }398399 private func resetReading() {400 if readingProgress != 0 { readingProgress = 0 }401 if isLongPage { isLongPage = false }402 if scrollDirection != .idle { scrollDirection = .idle }403 if !isAtTop { isAtTop = true }404 lastOffsetY = 0405 scrollTravel = 0406 }407408 // MARK: Events from the coordinator409410 fileprivate func didCommit() {411 guard let view = webView else { return }412 failure = nil413 readerArticle = nil414 syncFromWebView()415 if let url, history.record(url: url, title: view.title ?? ""), !isPrivate { environment.dataChanged() }416 recordFlowStep()417 resetReading()418 }419420 /// AURA Flow: remembers how this page was reached. A private tab keeps its trail in memory only.421 private func recordFlowStep() {422 let transition = pendingTransition423 pendingTransition = nil424 guard environment.settings.flowEnabled, let url, HistoryStore.isRecordable(url) || isSearchPage else { return }425 let tabID = id, opener = openerID, text = url.absoluteString, pageTitle = searchQuery ?? title426 flow.update { trail in427 let effective: FlowTransition428 if trail.cursor[tabID] == nil, let opener, trail.cursor[opener] != nil, transition != .typed { effective = .opened(from: opener) }429 else { effective = transition ?? .link }430 trail.record(url: text, title: pageTitle, tabID: tabID, transition: effective)431 }432 model.flowDidChange()433 }434435 /// True (once) when `candidate` is a load the app started for a link rather than for a typed address.436 fileprivate func consumeLinkLoad(_ candidate: URL) -> Bool {437 guard let expected = linkLoadURL else { return false }438 let matches = expected == candidate || expected.absoluteString == candidate.absoluteString || (expected.host == candidate.host && expected.path == candidate.path)439 if matches { linkLoadURL = nil }440 return matches441 }442443 fileprivate func didFail(_ error: Error, url failedURL: URL?) {444 guard !PageFailure.isBenign(error) else { return }445 failure = PageFailure(error: error, url: failedURL ?? url)446 if let failedURL { url = failedURL }447 isLoading = false448 webView?.scrollView.refreshControl?.endRefreshing()449 model.tabStateDidChange(self)450 }451452 fileprivate func consumeUserInitiated(_ candidate: URL?) -> Bool {453 guard let expected = userInitiatedURL, let candidate else { return false }454 let matches = expected == candidate || expected.absoluteString == candidate.absoluteString || (expected.host == candidate.host && expected.path == candidate.path)455 if matches { userInitiatedURL = nil }456 return matches457 }458}459460/// WebKit delegate of one tab (held weakly by nothing but the tab; holds the tab weakly).461@MainActor462final class MobileTabCoordinator: NSObject, WKNavigationDelegate, WKUIDelegate {463 private weak var tab: MobileTab?464 init(tab: MobileTab) { self.tab = tab }465466 @objc func pulledToRefresh(_ sender: UIRefreshControl) {467 tab?.reload()468 DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { sender.endRefreshing() }469 }470471 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences) async -> (WKNavigationActionPolicy, WKWebpagePreferences) {472 guard let tab, let url = navigationAction.request.url else { return (.cancel, preferences) }473 let isMainFrame = navigationAction.targetFrame?.isMainFrame ?? true474 let typed = isMainFrame && tab.consumeUserInitiated(url)475 if isMainFrame {476 let followsLink = tab.consumeLinkLoad(url)477 switch navigationAction.navigationType {478 case .backForward, .reload: tab.pendingTransition = .revisit479 default: tab.pendingTransition = typed && !followsLink ? .typed : .link480 }481 }482483 if navigationAction.shouldPerformDownload, ["data", "blob", "http", "https"].contains(url.scheme?.lowercased() ?? "") { return (.download, preferences) }484485 // Native search pages are opened by the user (address bar, results page, back/forward), never by web content.486 if SPSearchURL.isSearch(url) {487 let fromSearch = SPSearchURL.isSearch(navigationAction.sourceFrame.request.url) || SPSearchURL.isSearch(webView.url)488 let allowed = isMainFrame && (typed || fromSearch || navigationAction.navigationType == .backForward || navigationAction.navigationType == .reload)489 return (allowed ? .allow : .cancel, preferences)490 }491492 switch URLSafety.verdict(for: url, isMainFrame: isMainFrame, typedByUser: typed, sourceIsFile: navigationAction.sourceFrame.request.url?.isFileURL ?? false) {493 case .block:494 if isMainFrame { tab.model.toast = L("A navigation to a “%@:” address was blocked.", url.scheme ?? "") }495 return (.cancel, preferences)496 case .external:497 tab.model.confirmExternal(url)498 return (.cancel, preferences)499 case .allow:500 break501 }502 return (.allow, preferences)503 }504505 func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse) async -> WKNavigationResponsePolicy {506 if let http = navigationResponse.response as? HTTPURLResponse, let disposition = http.value(forHTTPHeaderField: "Content-Disposition"),507 disposition.lowercased().hasPrefix("attachment") { return .download }508 return navigationResponse.canShowMIMEType ? .allow : .download509 }510511 func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { adopt(download) }512 func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { adopt(download) }513514 private func adopt(_ download: WKDownload) {515 guard let tab else { return }516 tab.model.environment.downloads.adopt(download, isPrivate: tab.isPrivate)517 tab.model.toast = L("Download started")518 }519520 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { tab?.failure = nil; tab?.syncFromWebView() }521 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { tab?.didCommit() }522 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { tab?.syncFromWebView() }523 func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {524 tab?.didFail(error, url: (error as NSError).userInfo[NSURLErrorFailingURLErrorKey] as? URL)525 }526 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { tab?.didFail(error, url: nil) }527 func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { webView.reload() }528529 // Windows opened by pages become tabs.530 func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {531 guard let tab else { return nil }532 if let url = navigationAction.request.url, !url.absoluteString.isEmpty, case .block = URLSafety.verdict(for: url, isMainFrame: true, typedByUser: false) { return nil }533 return tab.model.openTab(from: tab, configuration: configuration).webView534 }535536 func webViewDidClose(_ webView: WKWebView) { if let tab { tab.model.close(tab) } }537538 // AURA Peek: a long press on a link shows what is behind it (fetched without cookies or scripts) and what can be done with it.539 func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo,540 completionHandler: @escaping @MainActor (UIContextMenuConfiguration?) -> Void) {541 guard let tab, let url = elementInfo.linkURL, Self.isWebLink(url) else { completionHandler(nil); return }542 completionHandler(tab.model.peekConfiguration(for: url, in: tab))543 }544545 /// Tapping the preview opens the link in this tab.546 func webView(_ webView: WKWebView, contextMenuForElement elementInfo: WKContextMenuElementInfo, willCommitWithAnimator animator: any UIContextMenuInteractionCommitAnimating) {547 guard let url = elementInfo.linkURL, Self.isWebLink(url) else { return }548 animator.addCompletion { [weak tab] in tab?.load(url, userInitiated: false) }549 }550551 private static func isWebLink(_ url: URL) -> Bool { ["http", "https"].contains(url.scheme?.lowercased() ?? "") }552553 // JavaScript dialogs554 private func present(_ alert: UIAlertController) -> Bool {555 guard let root = MobileEnvironment.keyWindow?.rootViewController else { return false }556 var top = root557 while let next = top.presentedViewController { top = next }558 top.present(alert, animated: true)559 return true560 }561562 private func originTitle(_ frame: WKFrameInfo) -> String {563 frame.securityOrigin.host.isEmpty ? L("This page says:") : L("%@ says:", frame.securityOrigin.host)564 }565566 func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async {567 await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in568 let alert = UIAlertController(title: originTitle(frame), message: String(message.prefix(2000)), preferredStyle: .alert)569 alert.addAction(UIAlertAction(title: L("OK"), style: .default) { _ in continuation.resume() })570 if !present(alert) { continuation.resume() }571 }572 }573574 func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async -> Bool {575 await withCheckedContinuation { continuation in576 let alert = UIAlertController(title: originTitle(frame), message: String(message.prefix(2000)), preferredStyle: .alert)577 alert.addAction(UIAlertAction(title: L("Cancel"), style: .cancel) { _ in continuation.resume(returning: false) })578 alert.addAction(UIAlertAction(title: L("OK"), style: .default) { _ in continuation.resume(returning: true) })579 if !present(alert) { continuation.resume(returning: false) }580 }581 }582583 func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo) async -> String? {584 await withCheckedContinuation { continuation in585 let alert = UIAlertController(title: originTitle(frame), message: String(prompt.prefix(2000)), preferredStyle: .alert)586 alert.addTextField { $0.text = defaultText }587 alert.addAction(UIAlertAction(title: L("Cancel"), style: .cancel) { _ in continuation.resume(returning: nil) })588 alert.addAction(UIAlertAction(title: L("OK"), style: .default) { [weak alert] _ in continuation.resume(returning: alert?.textFields?.first?.text) })589 if !present(alert) { continuation.resume(returning: nil) }590 }591 }592593 /// Camera and microphone: the system asks the user for each site.594 func webView(_ webView: WKWebView, decideMediaCapturePermissionsFor origin: WKSecurityOrigin, initiatedBy frame: WKFrameInfo, type: WKMediaCaptureType) async -> WKPermissionDecision {595 frame.isMainFrame || origin.host == webView.url?.host ? .prompt : .deny596 }597}598