Repository Public License
1import Foundation2import NavigatorCore3import Persistence45/// What Focus hid when it started, so that ending the session puts the window back exactly as it was.6public struct FocusRestoration: Sendable, Equatable, Codable {7 public var windowID: WindowID8 public var wasSidebarCollapsed: Bool9 public var wasAgentPanelOpen: Bool10 public var tabLayout: TabLayoutMode1112 public init(window: BrowserWindow) {13 windowID = window.id; wasSidebarCollapsed = window.isSidebarCollapsed14 wasAgentPanelOpen = window.isAgentPanelOpen; tabLayout = window.tabLayout15 }1617 /// The window with the chrome Focus hid shown again. Changes the user made to other properties during the18 /// session (frame, selected tab, split) are kept.19 public func restoring(_ window: BrowserWindow) -> BrowserWindow {20 var copy = window21 copy.isSidebarCollapsed = wasSidebarCollapsed22 copy.isAgentPanelOpen = wasAgentPanelOpen23 copy.tabLayout = tabLayout24 return copy25 }26}2728/// Pure state machine of one focus session. Time never comes from the system clock: every transition takes29/// `now`, so the timer is exact and testable.30public struct FocusSession: Sendable, Equatable {31 public enum Phase: String, Sendable, Codable { case idle, running, paused, finished }32 public enum EndReason: String, Sendable, Codable { case timerElapsed, endedByUser }3334 public enum TransitionError: Error, Sendable, Equatable {35 /// The transition is not allowed from the current phase.36 case invalid(from: Phase)37 }3839 public private(set) var phase: Phase = .idle40 /// Planned length; `nil` = no timer (the session lasts until the user ends it).41 public private(set) var duration: TimeInterval?42 public private(set) var startedAt: Date?43 public private(set) var endedAt: Date?44 public private(set) var endReason: EndReason?45 /// Focused time accumulated before the current running stretch.46 private var accumulated: TimeInterval = 047 private var resumedAt: Date?4849 public init() {}5051 public mutating func start(duration: TimeInterval?, now: Date) throws(TransitionError) {52 guard phase == .idle || phase == .finished else { throw .invalid(from: phase) }53 self = FocusSession()54 phase = .running55 self.duration = duration.flatMap { $0 > 0 ? $0 : nil }56 startedAt = now57 resumedAt = now58 }5960 public mutating func pause(now: Date) throws(TransitionError) {61 refresh(now: now)62 guard phase == .running else { throw .invalid(from: phase) }63 accumulated = elapsed(now: now)64 resumedAt = nil65 phase = .paused66 }6768 public mutating func resume(now: Date) throws(TransitionError) {69 guard phase == .paused else { throw .invalid(from: phase) }70 resumedAt = now71 phase = .running72 }7374 public mutating func end(now: Date) throws(TransitionError) {75 refresh(now: now)76 guard phase == .running || phase == .paused else { throw .invalid(from: phase) }77 finish(.endedByUser, at: now)78 }7980 /// Finishes the session when its timer has run out. Call before reading `phase` on a timer tick or when81 /// the app comes back to the foreground. Returns `true` when this call ended the session.82 @discardableResult83 public mutating func refresh(now: Date) -> Bool {84 guard phase == .running, let duration, let resumedAt else { return false }85 guard elapsed(now: now) >= duration else { return false }86 // The session ended when the timer ran out, not when somebody noticed.87 finish(.timerElapsed, at: resumedAt.addingTimeInterval(duration - accumulated))88 return true89 }9091 private mutating func finish(_ reason: EndReason, at date: Date) {92 accumulated = min(elapsed(now: date), duration ?? .infinity)93 resumedAt = nil94 phase = .finished95 endedAt = date96 endReason = reason97 }9899 /// Focused time so far (pauses excluded), capped at the duration.100 public func elapsed(now: Date) -> TimeInterval {101 let running = resumedAt.map { max(now.timeIntervalSince($0), 0) } ?? 0102 return min(accumulated + running, duration ?? .infinity)103 }104105 /// Time left on the timer; `nil` without a timer or outside a session.106 public func remaining(now: Date) -> TimeInterval? {107 guard let duration, phase == .running || phase == .paused else { return nil }108 return max(duration - elapsed(now: now), 0)109 }110111 /// When the timer will run out if the session keeps running; `nil` when paused or without a timer.112 /// The UI schedules its wake-up for this date.113 public func deadline(now: Date) -> Date? {114 guard phase == .running, let remaining = remaining(now: now) else { return nil }115 return now.addingTimeInterval(remaining)116 }117118 public var isActive: Bool { phase == .running || phase == .paused }119}120121/// Snapshot handed to the UI.122public struct FocusStatus: Sendable, Equatable {123 public var spaceID: SpaceID124 public var session: FocusSession125 public var settings: FocusSettings126 public var remaining: TimeInterval?127 public var deadline: Date?128}129130public enum FocusError: Error, Sendable, Equatable {131 case spaceNotFound132 case noActiveSession133 case invalidTransition(from: FocusSession.Phase)134}135136/// Focus sessions of the running app, one per space at most, plus the per-space settings stored with the space.137///138/// A session lives in memory: it does not survive a relaunch (the window chrome is restored from the stored139/// window state, which Focus never overwrites — it only asks the UI to hide things while a session is active).140public actor FocusController {141 private struct Active {142 var session: FocusSession143 var restorations: [FocusRestoration]144 }145146 private let database: NavigatorDatabase147 private let now: @Sendable () -> Date148 private var active: [SpaceID: Active] = [:]149 /// Settings of ghost spaces, which are never stored.150 private var ghostSettings: [SpaceID: FocusSettings] = [:]151152 public init(database: NavigatorDatabase, now: @escaping @Sendable () -> Date = { .now }) {153 self.database = database154 self.now = now155 }156157 // MARK: Settings158159 public func settings(for space: SpaceID) async throws -> FocusSettings {160 if database.ghosts.contains(space.raw) { return ghostSettings[space] ?? FocusSettings() }161 guard let stored = try await database.spaces.space(space) else { throw FocusError.spaceNotFound }162 return stored.focus163 }164165 /// Stores the settings with the space (in memory for a ghost space).166 public func updateSettings(_ settings: FocusSettings, for space: SpaceID) async throws {167 var settings = settings168 if let seconds = settings.timerSeconds, seconds <= 0 { settings.timerSeconds = nil }169 if database.ghosts.contains(space.raw) { ghostSettings[space] = settings; return }170 guard var stored = try await database.spaces.space(space) else { throw FocusError.spaceNotFound }171 stored.focus = settings172 stored.updatedAt = now()173 try await database.spaces.save(stored)174 }175176 // MARK: Session177178 /// Starts a session for the space with its stored settings (the timer can be overridden for this session).179 /// `windows` are the space's open windows: their chrome state is remembered for `end`.180 @discardableResult181 public func start(space: SpaceID, windows: [BrowserWindow], timerSeconds: Int?? = nil) async throws -> FocusStatus {182 let settings = try await settings(for: space)183 var entry = active[space] ?? Active(session: FocusSession(), restorations: [])184 _ = entry.session.refresh(now: now())185 let seconds = timerSeconds ?? settings.timerSeconds186 do { try entry.session.start(duration: seconds.map(TimeInterval.init), now: now()) } catch {187 throw FocusError.invalidTransition(from: entry.session.phase)188 }189 entry.restorations = windows.filter { $0.spaceID == space }.map(FocusRestoration.init(window:))190 active[space] = entry191 return status(space: space, entry: entry, settings: settings)192 }193194 @discardableResult195 public func pause(space: SpaceID) async throws -> FocusStatus {196 try await transition(space) { session, now throws(FocusSession.TransitionError) in try session.pause(now: now) }197 }198199 @discardableResult200 public func resume(space: SpaceID) async throws -> FocusStatus {201 try await transition(space) { session, now throws(FocusSession.TransitionError) in try session.resume(now: now) }202 }203204 /// Ends the session and returns what to restore. Also the way to acknowledge a session whose timer ran out.205 @discardableResult206 public func end(space: SpaceID) async throws -> [FocusRestoration] {207 guard var entry = active[space] else { throw FocusError.noActiveSession }208 _ = entry.session.refresh(now: now())209 if entry.session.isActive { try? entry.session.end(now: now()) }210 active[space] = nil211 return entry.restorations212 }213214 /// Current state, with the timer applied. `nil` when the space has no session.215 public func status(space: SpaceID) async throws -> FocusStatus? {216 guard var entry = active[space] else { return nil }217 if entry.session.refresh(now: now()) { active[space] = entry }218 return status(space: space, entry: entry, settings: try await settings(for: space))219 }220221 /// Spaces with a running or paused session.222 public func activeSpaces() -> [SpaceID] {223 let date = now()224 return active.filter { _, entry in225 var session = entry.session226 session.refresh(now: date)227 return session.isActive228 }.map(\.key).sorted()229 }230231 /// Whether the UI should currently hide chrome for a space, and what.232 public func presentation(space: SpaceID) async throws -> (hidesTabStrip: Bool, hidesSidebar: Bool) {233 guard let status = try await status(space: space), status.session.isActive else { return (false, false) }234 return (status.settings.hidesTabStrip, status.settings.hidesSidebar)235 }236237 /// Drops the state kept for a ghost space when its window closes.238 public func forgetGhost(space: SpaceID) {239 ghostSettings[space] = nil240 active[space] = nil241 }242243 private func transition(_ space: SpaceID,244 _ body: (inout FocusSession, Date) throws(FocusSession.TransitionError) -> Void) async throws -> FocusStatus {245 guard var entry = active[space] else { throw FocusError.noActiveSession }246 do { try body(&entry.session, now()) } catch {247 active[space] = entry248 throw FocusError.invalidTransition(from: entry.session.phase)249 }250 active[space] = entry251 return status(space: space, entry: entry, settings: try await settings(for: space))252 }253254 private func status(space: SpaceID, entry: Active, settings: FocusSettings) -> FocusStatus {255 let date = now()256 return FocusStatus(spaceID: space, session: entry.session, settings: settings,257 remaining: entry.session.remaining(now: date), deadline: entry.session.deadline(now: date))258 }259}260