Repository Public License
1import Foundation2import NavigatorCore3import Persistence45/// What a private window promises. Every flag is `false`; the type exists so each module asks the same6/// question the same way (`GhostPolicy.recordsHistory`) and tests can pin the answers.7public enum GhostPolicy {8 public static let persistsProfile = false9 public static let persistsWindowsAndTabs = false10 public static let recordsHistory = false11 public static let indexesMemory = false12 public static let syncs = false13 public static let persistsPermissions = false14 public static let persistsDownloadList = false15 public static let persistsShieldStatistics = false16 public static let usesPersistentWebsiteData = false17}1819public enum GhostError: Error, Sendable, Equatable {20 case sessionEnded21 case windowNotFound22 case tabNotFound23}2425/// What the app must tear down when a private session ends.26public struct GhostTeardown: Sendable, Equatable {27 public var profileID: ProfileID28 /// Identifier of the session's WebKit data store. The web layer must have created it as a **non-persistent**29 /// store; it is reported so that layer can assert nothing was written under this identifier.30 public var dataStoreIdentifier: UUID31 public var spaceIDs: [SpaceID]32 public var windowIDs: [WindowID]33 public var tabIDs: [TabID]34}3536/// One private browsing session: an in-memory ghost profile with its space, windows and tabs.37///38/// Everything lives in this actor. The profile, the space and every window are declared in39/// `database.ghosts`, so any store that is handed one of them refuses the write with40/// `PersistenceError.ghostWriteRejected`; the services of this package additionally check the registry and keep41/// private state in memory. Ending the session forgets the registry entries and returns what the UI and the42/// web layer must discard (web views, the non-persistent data store).43///44/// The session offers the same tab operations a normal window has, on in-memory values. It deliberately has no45/// "reopen closed tab": a closed private tab is gone.46public actor GhostSession {47 public nonisolated let profile: Profile48 public nonisolated let space: OrbitSpace49 public nonisolated let startedAt: Date5051 private let database: NavigatorDatabase52 private let now: @Sendable () -> Date53 private var windowsByID: [WindowID: BrowserWindow] = [:]54 private var tabsByID: [TabID: Tab] = [:]55 private var closedWindows: [WindowID] = []56 private var ended = false5758 /// Creates the ghost profile and its single space and declares them. Nothing is written anywhere.59 public init(database: NavigatorDatabase, name: String = "Private", tint: SpaceTint = .silver,60 now: @escaping @Sendable () -> Date = { .now }) {61 self.database = database62 self.now = now63 let date = now()64 let profile = Profile(name: name, kind: .ghost, tint: tint, createdAt: date)65 let space = OrbitSpace(profileID: profile.id, name: name, symbol: "orix.ghost", tint: tint, createdAt: date, updatedAt: date)66 self.profile = profile67 self.space = space68 self.startedAt = date69 database.ghosts.declare(profile: profile.id, spaces: [space.id])70 }7172 public var isActive: Bool { !ended }73 public var windows: [BrowserWindow] { windowsByID.values.sorted { ($0.order, $0.id) < ($1.order, $1.id) } }7475 private func requireActive() throws { if ended { throw GhostError.sessionEnded } }7677 // MARK: Windows7879 @discardableResult80 public func openWindow(tabLayout: TabLayoutMode = .vertical, frame: WindowFrame? = nil) throws -> BrowserWindow {81 try requireActive()82 let window = BrowserWindow(spaceID: space.id, frame: frame, tabLayout: tabLayout,83 order: (windowsByID.values.map(\.order).max() ?? -1) + 1)84 database.ghosts.declare(window: window.id)85 windowsByID[window.id] = window86 return window87 }8889 public func window(_ id: WindowID) -> BrowserWindow? { windowsByID[id] }9091 /// Replaces the stored value of a window (selection, split, frame…).92 public func update(_ window: BrowserWindow) throws {93 try requireActive()94 guard windowsByID[window.id] != nil else { throw GhostError.windowNotFound }95 var copy = window96 copy.spaceID = space.id97 windowsByID[window.id] = copy98 }99100 /// Closes a window and discards its tabs. Returns the ids of the discarded tabs.101 @discardableResult102 public func closeWindow(_ id: WindowID) throws -> [TabID] {103 guard windowsByID.removeValue(forKey: id) != nil else { throw GhostError.windowNotFound }104 let gone = tabsByID.values.filter { $0.windowID == id }.map(\.id)105 for tab in gone { tabsByID[tab] = nil }106 // The window stays declared until the session ends: a late write for it must still be refused as ghost.107 closedWindows.append(id)108 return gone109 }110111 // MARK: Tabs112113 /// Open tabs of a window in display order (pinned first).114 public func tabs(in window: WindowID) -> [Tab] {115 tabsByID.values.filter { $0.windowID == window }.sorted { lhs, rhs in116 if lhs.isPinned != rhs.isPinned { return lhs.isPinned }117 return (lhs.order, lhs.createdAt, lhs.id) < (rhs.order, rhs.createdAt, rhs.id)118 }119 }120121 public func tab(_ id: TabID) -> Tab? { tabsByID[id] }122 public var tabCount: Int { tabsByID.count }123124 @discardableResult125 public func openTab(in window: WindowID, url: URL?, title: String = "", parent: TabID? = nil, select: Bool = true) throws -> Tab {126 try requireActive()127 guard var owner = windowsByID[window] else { throw GhostError.windowNotFound }128 let date = now()129 let order = (tabsByID.values.filter { $0.windowID == window && !$0.isPinned }.map(\.order).max() ?? -1) + 1130 let tab = Tab(windowID: window, spaceID: space.id, parentID: parent, url: url, title: title, order: order,131 lifecycle: .live, createdAt: date, lastActiveAt: date)132 tabsByID[tab.id] = tab133 if select { owner.selectedTabID = tab.id; windowsByID[window] = owner }134 return tab135 }136137 /// Replaces the stored value of a tab (URL, title, pinned, order…). The tab cannot leave the session.138 public func update(_ tab: Tab) throws {139 try requireActive()140 guard tabsByID[tab.id] != nil else { throw GhostError.tabNotFound }141 guard windowsByID[tab.windowID] != nil else { throw GhostError.windowNotFound }142 var copy = tab143 copy.spaceID = space.id144 copy.groupID = nil145 tabsByID[tab.id] = copy146 }147148 /// Navigation committed or title changed.149 public func touch(_ id: TabID, url: URL?, title: String) throws {150 guard var tab = tabsByID[id] else { throw GhostError.tabNotFound }151 tab.url = url; tab.title = title; tab.lastActiveAt = now()152 tabsByID[id] = tab153 }154155 /// Sets the display order of the unpinned (or pinned) tabs of a window.156 public func reorderTabs(in window: WindowID, _ ids: [TabID]) throws {157 guard windowsByID[window] != nil else { throw GhostError.windowNotFound }158 for (index, id) in ids.enumerated() where tabsByID[id]?.windowID == window { tabsByID[id]?.order = index }159 }160161 /// Closes a tab for good. Returns the window with its selection moved to the neighbouring tab.162 @discardableResult163 public func closeTab(_ id: TabID) throws -> BrowserWindow {164 guard let tab = tabsByID[id] else { throw GhostError.tabNotFound }165 guard var window = windowsByID[tab.windowID] else { throw GhostError.windowNotFound }166 let order = tabs(in: tab.windowID).map(\.id)167 tabsByID[id] = nil168 for child in tabsByID.values where child.parentID == id { tabsByID[child.id]?.parentID = tab.parentID }169 if let split = window.split, split.panes.contains(id) {170 let panes = split.panes.filter { $0 != id }171 window.split = panes.count >= 2 ? SplitLayout(axis: split.axis, panes: panes) : nil172 }173 if window.selectedTabID == id {174 let index = order.firstIndex(of: id) ?? 0175 window.selectedTabID = index + 1 < order.count ? order[index + 1] : (index > 0 ? order[index - 1] : nil)176 }177 windowsByID[window.id] = window178 return window179 }180181 // MARK: Ending182183 /// Ends the session: forgets every window and tab and the registry entries. Idempotent.184 @discardableResult185 public func end() -> GhostTeardown {186 let teardown = GhostTeardown(profileID: profile.id, dataStoreIdentifier: profile.dataStoreIdentifier,187 spaceIDs: [space.id], windowIDs: windowsByID.keys.sorted(), tabIDs: tabsByID.keys.sorted())188 ended = true189 database.ghosts.forget(profile: profile.id, spaces: [space.id], windows: Array(windowsByID.keys) + closedWindows)190 closedWindows.removeAll()191 windowsByID.removeAll()192 tabsByID.removeAll()193 return teardown194 }195}196197/// The private sessions of the running app.198public actor GhostSessionManager {199 private let database: NavigatorDatabase200 private let now: @Sendable () -> Date201 private var sessions: [ProfileID: GhostSession] = [:]202203 public init(database: NavigatorDatabase, now: @escaping @Sendable () -> Date = { .now }) {204 self.database = database205 self.now = now206 }207208 /// Starts a private session. Each one has its own profile, hence its own (non-persistent) website data:209 /// two private windows opened separately do not share cookies.210 public func begin(name: String = "Private") -> GhostSession {211 let session = GhostSession(database: database, name: name, now: now)212 sessions[session.profile.id] = session213 return session214 }215216 public func session(for profile: ProfileID) -> GhostSession? { sessions[profile] }217 public var activeSessions: [GhostSession] { sessions.values.sorted { $0.startedAt < $1.startedAt } }218 public func isGhost(_ profile: ProfileID) -> Bool { sessions[profile] != nil }219220 /// Ends one session and tells the other services to drop what they kept in memory for it.221 @discardableResult222 public func end(_ profile: ProfileID, permissions: PermissionService? = nil, shield: ShieldService? = nil) async -> GhostTeardown? {223 guard let session = sessions.removeValue(forKey: profile) else { return nil }224 let teardown = await session.end()225 await permissions?.endGhostSession(profile: profile)226 await shield?.forgetGhost(profile: profile)227 return teardown228 }229230 /// Ends every session (the app quits).231 public func endAll(permissions: PermissionService? = nil, shield: ShieldService? = nil) async -> [GhostTeardown] {232 var result: [GhostTeardown] = []233 for profile in Array(sessions.keys) {234 if let teardown = await end(profile, permissions: permissions, shield: shield) { result.append(teardown) }235 }236 return result237 }238}239