Repository Public
1import SwiftUI2import UIKit3import WebKit45enum LibrarySection: String, CaseIterable, Identifiable {6 case bookmarks, readingList, history, downloads7 var id: String { rawValue }8 var title: String {9 switch self {10 case .bookmarks: return L("Bookmarks")11 case .readingList: return L("Reading List")12 case .history: return L("History")13 case .downloads: return L("Downloads")14 }15 }16 var symbol: String {17 switch self {18 case .bookmarks: return "bookmark"19 case .readingList: return "eyeglasses"20 case .history: return "clock"21 case .downloads: return "arrow.down.circle"22 }23 }24}2526/// The tabs and transient UI state of one scene (one iPhone screen, or one iPad window).27@MainActor28@Observable29final class BrowserModel {30 @ObservationIgnored let environment: MobileEnvironment31 private(set) var tabs: [MobileTab] = []32 private(set) var selectedTabID: UUID?33 private(set) var recentlyClosed: [TabSnapshot] = []34 /// True while the private tab set is the one on screen.35 var showsPrivate = false3637 // Transient UI38 var isEditingAddress = false39 var showsTabOverview = false40 var library: LibrarySection?41 var showsSettings = false42 var showsAccount = false43 var bookmarkDraft: BookmarkDraft?44 /// In Focus Mode confirmations are held back (when the user asked for that); errors always show.45 var toast: String? {46 didSet {47 if let toast, focusMode, environment.settings.focusHidesDistractions, AuraToast.symbol(for: toast) == "checkmark.circle" { self.toast = nil }48 }49 }50 var pendingExternal: URL?5152 // AURA surfaces (per scene, so every iPad window has its own)53 enum AuraSurface: String, Identifiable, Sendable {54 case constellation, flow, canvas, portal55 var id: String { rawValue }56 }57 var auraSurface: AuraSurface?58 /// Constellation opened from the tab overview (it is presented over it and returns to it).59 var showsOverviewConstellation = false60 var showsOrbit = false61 var showsPalette = false62 var palettePrefill = ""63 /// Focus Mode: the chrome steps aside, a discreet pill remains.64 var focusMode = false65 /// Bumped when the Flow trail changes, so the map redraws.66 private(set) var flowRevision = 067 /// Flow of private tabs: in memory, never written to disk, discarded with the last private tab.68 @ObservationIgnored private(set) var privateFlow = FlowStore(url: nil)69 @ObservationIgnored var canvasController: CanvasController?70 @ObservationIgnored var recentCommands: [CommandID] = []7172 /// History of private tabs: in memory, never written to disk, discarded with the last private tab.73 @ObservationIgnored private(set) var privateHistory: HistoryStore74 @ObservationIgnored private(set) var privateDataStore: WKWebsiteDataStore = .nonPersistent()7576 struct BookmarkDraft: Identifiable {77 let id = UUID()78 var existing: Bookmark?79 var title: String80 var url: String81 var parentID: String?82 }8384 init(environment: MobileEnvironment) {85 self.environment = environment86 privateHistory = HistoryStore(db: try! ProfileSchema.open(at: nil))87 }8889 // MARK: Derived9091 var selectedTab: MobileTab? { tabs.first { $0.id == selectedTabID } }92 var regularTabs: [MobileTab] { tabs.filter { !$0.isPrivate } }93 var privateTabs: [MobileTab] { tabs.filter(\.isPrivate) }94 var visibleTabs: [MobileTab] { showsPrivate ? privateTabs : regularTabs }95 var isPrivate: Bool { selectedTab?.isPrivate ?? showsPrivate }9697 // MARK: Tabs9899 @discardableResult100 func newTab(url: URL? = nil, isPrivate: Bool? = nil, select: Bool = true, after: MobileTab? = nil) -> MobileTab {101 let tab = MobileTab(model: self, isPrivate: isPrivate ?? after?.isPrivate ?? showsPrivate)102 tab.openerID = after?.id103 if let after, let index = tabs.firstIndex(where: { $0.id == after.id }) { tabs.insert(tab, at: index + 1) } else { tabs.append(tab) }104 // A tab opened from another follows a link of that tab: Flow attaches it to the opener's path.105 if let url { tab.load(url, userInitiated: after == nil) }106 if select { self.select(tab) }107 stateChanged()108 return tab109 }110111 /// A tab for a window opened by a page; the web view must use exactly the configuration WebKit provides.112 func openTab(from parent: MobileTab, configuration: WKWebViewConfiguration) -> MobileTab {113 let tab = MobileTab(model: self, isPrivate: parent.isPrivate)114 tab.openerID = parent.id115 if let index = tabs.firstIndex(where: { $0.id == parent.id }) { tabs.insert(tab, at: index + 1) } else { tabs.append(tab) }116 tab.ensureWebView(adopting: configuration)117 select(tab)118 return tab119 }120121 func select(_ tab: MobileTab) {122 guard tabs.contains(where: { $0.id == tab.id }) else { return }123 if let previous = selectedTab, previous.id != tab.id { previous.captureThumbnail(); previous.lastActive = Date() }124 selectedTabID = tab.id125 showsPrivate = tab.isPrivate126 tab.lastActive = Date()127 if tab.url != nil { tab.ensureWebView() }128 stateChanged()129 }130131 func close(_ tab: MobileTab) {132 guard let index = tabs.firstIndex(where: { $0.id == tab.id }) else { return }133 // Private tabs leave no trace: they cannot be reopened.134 if !tab.isPrivate, let url = tab.url, HistoryStore.isRecordable(url) {135 recentlyClosed.insert(tab.snapshot(), at: 0)136 if recentlyClosed.count > 25 { recentlyClosed.removeLast() }137 }138 let wasSelected = selectedTabID == tab.id139 tab.tearDownWebView()140 tabs.remove(at: index)141 let closedID = tab.id, flow = tab.isPrivate ? privateFlow : environment.flow142 if flow.trail.cursor[closedID] != nil { flow.update { $0.tabClosed(closedID) } }143 if tab.isPrivate, privateTabs.isEmpty { endPrivateSession() }144 if wasSelected {145 let siblings = tab.isPrivate ? privateTabs : regularTabs146 if let next = siblings.last(where: { candidate in (tabs.firstIndex { $0.id == candidate.id } ?? 0) < index }) ?? siblings.first {147 select(next)148 } else if let other = regularTabs.last {149 select(other)150 } else {151 showsPrivate = false152 newTab(isPrivate: false)153 }154 }155 stateChanged()156 }157158 func closeAll(private closePrivate: Bool) {159 tabs.filter { $0.isPrivate == closePrivate }.forEach(close)160 }161162 /// The last private tab closed: cookies, site data, private history and cached private searches are discarded.163 private func endPrivateSession() {164 privateDataStore = .nonPersistent()165 privateHistory = HistoryStore(db: try! ProfileSchema.open(at: nil))166 privateFlow = FlowStore(url: nil)167 flowRevision += 1168 environment.downloads.forgetPrivateItems()169 Task { [search = environment.services.search] in await search.clearCache() }170 }171172 func reopenClosedTab() {173 guard !recentlyClosed.isEmpty else { return }174 reopen(recentlyClosed.removeFirst())175 }176177 func reopen(_ snapshot: TabSnapshot) {178 recentlyClosed.removeAll { $0.id == snapshot.id }179 var copy = snapshot180 copy.id = UUID()181 let tab = MobileTab(snapshot: copy, model: self)182 tabs.append(tab)183 select(tab)184 }185186 func selectAdjacentTab(offset: Int) {187 let list = visibleTabs188 guard list.count > 1, let current = list.firstIndex(where: { $0.id == selectedTabID }) else { return }189 select(list[(current + offset + list.count) % list.count])190 PlatformActions.haptic()191 }192193 /// Switches between regular and private tab sets, creating a first private tab on demand.194 func setPrivate(_ value: Bool) {195 guard value != showsPrivate || selectedTab?.isPrivate != value else { return }196 showsPrivate = value197 if let existing = (value ? privateTabs : regularTabs).max(by: { $0.lastActive < $1.lastActive }) { select(existing) } else { newTab(isPrivate: value) }198 }199200 func suspendBackgroundTabs(keeping count: Int = 6) {201 let loaded = tabs.filter { $0.webView != nil && $0.id != selectedTabID }.sorted { $0.lastActive > $1.lastActive }202 loaded.dropFirst(count).forEach { $0.suspend() }203 }204205 // MARK: Navigation206207 /// Resolves what was typed: an address is loaded, anything else is searched with the default engine (SP Search).208 func navigate(_ text: String, in tab: MobileTab? = nil) {209 let settings = environment.settings210 guard let resolved = AddressResolver.resolve(text, engine: settings.activeSearchEngine(), engines: settings.allSearchEngines()) else { return }211 let target = tab ?? selectedTab ?? newTab()212 target.load(resolved.url)213 isEditingAddress = false214 stateChanged()215 }216217 func open(_ url: URL, inNewTab: Bool = false) {218 if inNewTab || selectedTab == nil { newTab(url: url) } else { selectedTab?.load(url) }219 library = nil220 showsTabOverview = false221 }222223 func searchActions(for tab: MobileTab) -> SearchActions {224 SearchActions(225 open: { [weak self, weak tab] url, disposition in226 guard let self, let tab else { return }227 switch disposition {228 case .current: tab.load(url)229 case .newTab: self.newTab(url: url, after: tab)230 case .backgroundTab: self.newTab(url: url, select: false, after: tab); self.toast = L("Opened in a background tab")231 }232 },233 search: { [weak tab] text, kind in tab?.search(text, kind: kind) },234 share: { [weak self] url in self?.share([url]) },235 saveImage: { [weak self] image in self?.saveImage(image) },236 addToReadingList: isPrivate ? nil : { [weak self] title, url in self?.addToReadingList(title: title, url: url.absoluteString) })237 }238239 func confirmExternal(_ url: URL) { pendingExternal = url }240241 // MARK: Library actions242243 func addToReadingList(title: String, url: String) {244 environment.services.library.addToReadingList(title: title, url: url)245 environment.dataChanged()246 toast = L("Added to Reading List")247 PlatformActions.haptic()248 }249250 func toggleFavorite(title: String, url: String) {251 let library = environment.services.library252 if library.isFavorite(url) { library.removeFavorite(url: url); toast = L("Removed from Favorites") }253 else { library.addFavorite(title: title, url: url); toast = L("Added to Favorites") }254 environment.dataChanged()255 PlatformActions.haptic()256 }257258 func bookmarkCurrentPage() {259 guard let tab = selectedTab, let url = tab.url, HistoryStore.isRecordable(url) else { return }260 let existing = environment.bookmarks.bookmarks(forURL: url.absoluteString).first261 bookmarkDraft = BookmarkDraft(existing: existing, title: existing?.title ?? tab.displayTitle, url: url.absoluteString, parentID: existing?.parentID)262 }263264 func share(_ items: [Any]) {265 guard let root = MobileEnvironment.keyWindow?.rootViewController else { return }266 var top = root267 while let next = top.presentedViewController { top = next }268 let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)269 controller.popoverPresentationController?.sourceView = top.view270 controller.popoverPresentationController?.sourceRect = CGRect(x: top.view.bounds.midX, y: top.view.bounds.maxY - 80, width: 1, height: 1)271 top.present(controller, animated: true)272 }273274 func saveImage(_ image: ImageResult) {275 guard let url = URL(string: image.imageURL) else { return }276 Task {277 do {278 let data = try await RemoteImageLoader.shared.data(from: url)279 let target = environment.downloads.destination(for: url.lastPathComponent.isEmpty ? "image" : url.lastPathComponent)280 try data.write(to: target, options: .atomic)281 toast = L("Image saved to Downloads")282 } catch {283 toast = L("The image could not be saved")284 }285 }286 }287288 // MARK: Session289290 func flowDidChange() { flowRevision += 1 }291292 func tabStateDidChange(_ tab: MobileTab) { if !tab.isPrivate { environment.scheduleSessionSave() } }293294 private func stateChanged() { environment.scheduleSessionSave() }295296 /// Only regular tabs are ever saved.297 func snapshot() -> WindowSnapshot {298 let regular = regularTabs299 return WindowSnapshot(tabs: regular.map { $0.snapshot() }, selectedTabID: regular.contains { $0.id == selectedTabID } ? selectedTabID : regular.last?.id)300 }301302 func restore(_ snapshot: WindowSnapshot) {303 tabs = snapshot.tabs.map { MobileTab(snapshot: $0, model: self) }304 if let selected = tabs.first(where: { $0.id == snapshot.selectedTabID }) ?? tabs.last { select(selected) }305 }306}307