Repository Public
1import AppKit2import WebKit34extension Notification.Name {5 static let spbShortcutsChanged = Notification.Name("SPBrowserShortcutsChanged")6}78/// Composition root: owns the stores and services and hands them to windows and tabs.9@MainActor10@Observable11final class AppEnvironment: EngineEnvironment {12 let root: URL13 let blocker = ContentBlockerService()14 let downloads: DownloadManager15 let profileStore: ProfileStore16 let sessionStore: SessionStore17 let secrets: SecretStore18 let aiHistory: AIConversationStore19 let settingsRecoveredFromCorruption: Bool20 /// SP Search, account and synchronization (shared with the iOS app).21 let services: BrowserServices2223 var settings: AppSettings {24 didSet {25 guard settings != oldValue else { return }26 settingsStore.settings = settings27 settingsDidChange(from: oldValue)28 }29 }30 var userScripts: [UserScript] {31 didSet { guard userScripts != oldValue else { return }; userScriptStore.value = userScripts; reinstallUserScripts() }32 }33 var blockLists: BlockListState {34 didSet { guard blockLists != oldValue else { return }; blockListStore.value = blockLists; refreshBlocker() }35 }36 private(set) var profiles: [Profile] = []37 private(set) var controllers: [BrowserWindowController] = []38 /// The pane shown in the Settings window.39 var settingsSection: SettingsSection = .general40 /// Set when the previous session file was damaged, so the first window can tell the user.41 var sessionRecoveryNote: String?4243 @ObservationIgnored private let settingsStore: SettingsStore44 @ObservationIgnored private let userScriptStore: JSONFileStore<[UserScript]>45 @ObservationIgnored private let blockListStore: JSONFileStore<BlockListState>46 @ObservationIgnored private var contexts: [UUID: ProfileContext] = [:]47 @ObservationIgnored private var saveTask: Task<Void, Never>?48 @ObservationIgnored private var maintenanceTimer: Timer?49 @ObservationIgnored var isTerminating = false5051 /// - Parameter root: storage directory. Tests and screenshots pass a temporary one; the app uses Application Support.52 init(root: URL, secrets: SecretStore = KeychainStore(), accountSecrets: SecretStore? = nil, backend: BackendConfiguration = .current()) {53 self.root = root54 try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)55 self.secrets = secrets56 settingsStore = SettingsStore(url: root.appendingPathComponent("settings.json"))57 settings = settingsStore.settings58 settingsRecoveredFromCorruption = settingsStore.recoveredFromCorruption59 userScriptStore = JSONFileStore(url: root.appendingPathComponent("user-scripts.json"), defaults: [])60 userScripts = userScriptStore.value61 blockListStore = JSONFileStore(url: root.appendingPathComponent("block-lists.json"), defaults: BlockListState())62 blockLists = blockListStore.value63 profileStore = ProfileStore(root: root.appendingPathComponent("Profiles", isDirectory: true))64 sessionStore = SessionStore(directory: root.appendingPathComponent("Sessions", isDirectory: true))65 downloads = DownloadManager(recordsURL: root.appendingPathComponent("downloads.json"))66 aiHistory = AIConversationStore(url: root.appendingPathComponent("intelligence-history.json"))67 profiles = profileStore.profiles68 // Account secrets (session token, device key, account key) live in their own keychain service.69 let accountStore: SecretStore = accountSecrets ?? ((secrets is KeychainStore) ? KeychainStore(service: "ai.spboucher.spbrowser.account") : InMemorySecretStore())70 // The setting is read through a box because `self` is not available until every stored property is set.71 final class Flag: @unchecked Sendable { var read: @MainActor () -> Bool = { true } }72 let flag = Flag()73 services = BrowserServices(root: root, secrets: accountStore,74 authorizer: SystemPasskeyAuthorizer(anchor: { NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible } }),75 device: Self.deviceDescription(), configuration: backend, syncEnabled: { flag.read() })76 flag.read = { [weak self] in self?.settings.syncEnabled ?? false }77 downloads.askWhereToSave = { [weak self] in self?.settings.askWhereToSaveDownloads ?? false }78 Log.setDiagnostics(enabled: settings.diagnosticsEnabled, directory: root)79 }8081 static func defaultRoot() -> URL {82 if let override = UserDefaults.standard.string(forKey: "SPBDataDir"), !override.isEmpty {83 return URL(fileURLWithPath: (override as NSString).expandingTildeInPath, isDirectory: true)84 }85 let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first86 ?? FileManager.default.temporaryDirectory87 return base.appendingPathComponent("SP Browser", isDirectory: true)88 }8990 static func deviceDescription() -> DeviceDescription {91 var size = 092 sysctlbyname("hw.model", nil, &size, nil, 0)93 var buffer = [CChar](repeating: 0, count: max(size, 1))94 sysctlbyname("hw.model", &buffer, &size, nil, 0)95 let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""96 let model = String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)97 return DeviceDescription(name: Host.current().localizedName ?? "Mac", platform: "macos", model: model, appVersion: version)98 }99100 /// Connects sync to the default profile and starts the scheduler. Other profiles and private windows stay local.101 private func startServices() {102 let context = defaultContext103 if !context.isPrivate { services.attach(history: context.history, bookmarks: context.bookmarks); services.attach(canvas: context.canvas) }104 services.onRemoteCanvasChange = { [weak self] in self?.controllers.forEach { $0.state.canvasController?.reload() } }105 services.tabsProvider = { [weak self] in106 guard let self else { return ([], []) }107 let regular = self.controllers.map(\.state).filter { !$0.isPrivate }108 let open = regular.flatMap(\.tabs).compactMap { tab -> RemoteTab? in109 guard let url = tab.url, HistoryStore.isRecordable(url) else { return nil }110 return RemoteTab(title: tab.displayTitle, url: url.absoluteString)111 }112 let closed = regular.flatMap(\.recentlyClosed).compactMap { snapshot -> RemoteTab? in113 guard let text = snapshot.url, let url = URL(string: text), HistoryStore.isRecordable(url) else { return nil }114 return RemoteTab(title: snapshot.title, url: text)115 }116 return (open, closed)117 }118 services.onRemoteProfileChange = { [weak self] changed in119 for state in self?.controllers.map(\.state) ?? [] {120 if changed.contains(SyncCollection.history) { state.historyRevision += 1 }121 if changed.contains(SyncCollection.bookmarks) { state.bookmarksRevision += 1 }122 }123 }124 services.sync.start()125 }126127 func applicationBecameActive() { if !isTerminating { services.sync.start() } }128 func applicationResignedActive() { services.sync.stop() }129130 // MARK: EngineEnvironment (search and sync)131132 func searchContext(isPrivate: Bool) -> SearchContext { services.searchContext(isPrivate: isPrivate) }133134 func browsingDataChanged() { services.sync.requestSync(after: 12) }135136 func start() {137 refreshBlocker()138 applyAppearance()139 startServices()140 maintenanceTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in141 Task { @MainActor in self?.suspendInactiveTabs() }142 }143 }144145 // MARK: Profiles146147 func context(for profile: Profile) -> ProfileContext? {148 if let existing = contexts[profile.id] { return existing }149 guard let context = try? ProfileContext(profile: profile, directory: profileStore.directory(for: profile)) else { return nil }150 contexts[profile.id] = context151 return context152 }153154 var defaultContext: ProfileContext {155 if let context = context(for: profileStore.defaultProfile) { return context }156 // The profile database could not be opened (disk full, permissions): keep browsing with an in-memory profile.157 if let memory = try? ProfileContext(privateFrom: ProfileContext(profile: profileStore.defaultProfile, directory: FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString))) {158 return memory159 }160 fatalError("SP Browser cannot create any storage, not even temporary.")161 }162163 @discardableResult164 func createProfile(name: String, colorIndex: Int) -> Profile {165 let profile = profileStore.create(name: name, colorIndex: colorIndex)166 profiles = profileStore.profiles167 return profile168 }169170 func updateProfile(_ profile: Profile) {171 profileStore.update(profile)172 profiles = profileStore.profiles173 }174175 /// Deletes a profile with its history, bookmarks and all website data. Its windows are closed first.176 func deleteProfile(_ profile: Profile) async {177 guard profile.id != profileStore.defaultID else { return }178 for controller in controllers where controller.state.profile.profile.id == profile.id { controller.close() }179 contexts[profile.id] = nil180 guard profileStore.delete(profile) else { return }181 profiles = profileStore.profiles182 // The store can only be removed once no web view uses it any more.183 try? await Task.sleep(for: .milliseconds(300))184 try? await WKWebsiteDataStore.remove(forIdentifier: profile.id)185 }186187 // MARK: Windows188189 @discardableResult190 func openWindow(profile: Profile? = nil, isPrivate: Bool = false, snapshot: WindowSnapshot? = nil, initialURL: URL? = nil) -> BrowserWindowController? {191 let target = profile ?? snapshot.flatMap { profileStore.profile(id: $0.profileID) } ?? profileStore.defaultProfile192 guard let base = context(for: target) ?? Optional(defaultContext) else { return nil }193 let context: ProfileContext194 if isPrivate {195 guard let privateContext = try? ProfileContext(privateFrom: base) else { return nil }196 context = privateContext197 } else {198 context = base199 }200 let state = BrowserWindowState(environment: self, profile: context)201 if let snapshot, !isPrivate { state.restore(snapshot) }202 if state.tabs.isEmpty { state.newTab(url: initialURL ?? homepageURL(), select: true) } else if let initialURL { state.newTab(url: initialURL, select: true) }203 let controller = BrowserWindowController(state: state, frameDescriptor: snapshot?.frame)204 controllers.append(controller)205 controller.showWindow(nil)206 controller.window?.makeKeyAndOrderFront(nil)207 return controller208 }209210 func windowDidClose(_ controller: BrowserWindowController) {211 controllers.removeAll { $0 === controller }212 if controller.state.isPrivate {213 // Closing the last reference to a non-persistent store discards its cookies and site data.214 if !controllers.contains(where: { $0.state.isPrivate }) {215 downloads.forgetPrivateItems()216 // Searches made in private windows only ever lived in the in-memory search cache: drop it too.217 Task { [search = services.search] in await search.clearCache() }218 }219 }220 if !isTerminating { scheduleSessionSave() }221 }222223 var keyState: BrowserWindowState? {224 (NSApp.keyWindow?.windowController as? BrowserWindowController)?.state225 ?? (NSApp.mainWindow?.windowController as? BrowserWindowController)?.state226 ?? controllers.last?.state227 }228229 func homepageURL() -> URL? {230 guard settings.newTabContent == .homepage else { return nil }231 return AddressResolver.resolve(settings.homepage, engine: settings.activeSearchEngine(), engines: settings.allSearchEngines())?.url232 }233234 /// Opens `url` in the frontmost regular window, creating one if needed (links from other apps, App Intents).235 func open(url: URL) {236 if let state = keyState, !state.isPrivate {237 state.newTab(url: url, select: true)238 state.window?.makeKeyAndOrderFront(nil)239 } else {240 openWindow(initialURL: url)241 }242 NSApp.activate(ignoringOtherApps: true)243 }244245 // MARK: Session246247 func sessionSnapshot() -> SessionSnapshot {248 SessionSnapshot(windows: controllers.filter { !$0.state.isPrivate }.map { $0.state.snapshot(frame: $0.window?.frameDescriptor) })249 }250251 func scheduleSessionSave() {252 guard !isTerminating else { return }253 saveTask?.cancel()254 saveTask = Task { [weak self] in255 try? await Task.sleep(for: .seconds(2))256 guard !Task.isCancelled else { return }257 self?.saveSessionNow()258 }259 }260261 func saveSessionNow() {262 do { try sessionStore.save(sessionSnapshot()) } catch { Log.event("session", "save failed: \(error.localizedDescription)") }263 // Open tabs changed: let the other devices know, without hurry.264 services.sync.requestSync(after: 10)265 }266267 /// Restores the previous windows. Returns false when there was nothing usable to restore.268 @discardableResult269 func restoreSession() -> Bool {270 let snapshot: SessionSnapshot271 switch sessionStore.load() {272 case .loaded(let s): snapshot = s273 case .recoveredFromBackup(let s):274 snapshot = s275 sessionRecoveryNote = L("The last session file was damaged. An earlier copy was restored.")276 case .corrupt:277 sessionRecoveryNote = L("The last session could not be read and was set aside. Starting with a new window.")278 return false279 case .empty: return false280 }281 let windows = snapshot.windows.filter { !$0.tabs.isEmpty }282 guard !windows.isEmpty else { return false }283 windows.forEach { openWindow(snapshot: $0) }284 return !controllers.isEmpty285 }286287 func restore(_ snapshot: SessionSnapshot) {288 snapshot.windows.filter { !$0.tabs.isEmpty }.forEach { openWindow(snapshot: $0) }289 }290291 // MARK: Reactions to settings292293 private func settingsDidChange(from old: AppSettings) {294 if old.contentBlockerEnabled != settings.contentBlockerEnabled || old.blockAds != settings.blockAds295 || old.blockTrackers != settings.blockTrackers || old.blockerDisabledHosts != settings.blockerDisabledHosts {296 refreshBlocker()297 }298 if old.appearance != settings.appearance { applyAppearance() }299 if old.syncEnabled != settings.syncEnabled { services.sync.accountStateChanged() }300 if old.shortcutOverrides != settings.shortcutOverrides { NotificationCenter.default.post(name: .spbShortcutsChanged, object: nil) }301 if old.diagnosticsEnabled != settings.diagnosticsEnabled { Log.setDiagnostics(enabled: settings.diagnosticsEnabled, directory: root) }302 if old.userScriptsEnabled != settings.userScriptsEnabled { reinstallUserScripts() }303 if old.customUserAgent != settings.customUserAgent {304 let agent = settings.customUserAgent.trimmingCharacters(in: .whitespaces)305 allTabs.forEach { $0.webView?.customUserAgent = agent.isEmpty ? nil : agent }306 }307 }308309 var allTabs: [BrowserTab] { controllers.flatMap(\.state.tabs) }310311 func refreshBlocker() {312 let settings = settings, lists = blockLists313 Task { await blocker.refresh(settings: settings, lists: lists) }314 }315316 private func reinstallUserScripts() {317 for tab in allTabs {318 guard let controller = tab.webView?.configuration.userContentController else { continue }319 UserScriptInjector.install(userScripts, enabled: settings.userScriptsEnabled && !tab.profile.isPrivate, into: controller)320 }321 }322323 private func applyAppearance() {324 switch settings.appearance {325 case .system: NSApp.appearance = nil326 case .light: NSApp.appearance = NSAppearance(named: .aqua)327 case .dark: NSApp.appearance = NSAppearance(named: .darkAqua)328 }329 }330331 private func suspendInactiveTabs() {332 let minutes = settings.suspendTabsAfterMinutes333 guard minutes > 0 else { return }334 controllers.forEach { $0.state.suspendInactiveTabs(olderThan: TimeInterval(minutes * 60)) }335 }336337 // MARK: Data removal338339 /// Removes every WebKit data store created under this environment. Used by tests and by "delete profile".340 func removeAllWebsiteDataStores() async {341 controllers.forEach { $0.close() }342 let ids = profiles.map(\.id)343 contexts.removeAll()344 try? await Task.sleep(for: .milliseconds(200))345 for id in ids { try? await WKWebsiteDataStore.remove(forIdentifier: id) }346 }347348 func clearHistory(since: Date?) {349 contexts.values.forEach { $0.history.clear(since: since); $0.flow.update { $0.forget(since: since) } }350 Task { await services.peek.clear() }351 // Clearing everything also clears what was searched; the deletions propagate to the other devices.352 if since == nil { services.clearSearchData() } else { services.localChange() }353 }354}355