SPB Git

Repository Public

SessionModels.swift 6.4 KB 168 lines swift

1import Foundation23struct TabSnapshot: Codable, Equatable, Identifiable, Sendable {4    var id: UUID = UUID()5    var url: String?6    var title: String = ""7    var isPinned: Bool = false8    var groupID: UUID?9    var workspaceID: UUID?10    /// Opaque WebKit back/forward state (`WKWebView.interactionState`), when available.11    var interactionState: Data?12    /// The tab this one was opened from (3.0). Absent in sessions saved by earlier versions.13    var openerID: UUID?14}1516struct TabGroup: Codable, Equatable, Identifiable, Sendable {17    var id: UUID = UUID()18    var name: String19    var colorIndex: Int = 020    var isCollapsed: Bool = false21}2223struct WorkspaceFavorite: Codable, Equatable, Identifiable, Sendable {24    var id: UUID = UUID()25    var title: String26    var url: String27}2829/// A named context ("Personal", "Research", "Development") that owns a set of tabs and favourites.30struct Workspace: Codable, Equatable, Identifiable, Sendable {31    var id: UUID = UUID()32    var name: String33    var symbol: String = "square.stack.3d.up"34    var colorIndex: Int = 035    var favorites: [WorkspaceFavorite] = []3637    static func defaults() -> [Workspace] {38        [39            Workspace(name: L("Personal"), symbol: "person", colorIndex: 0),40            Workspace(name: L("Research"), symbol: "books.vertical", colorIndex: 1),41            Workspace(name: L("Development"), symbol: "hammer", colorIndex: 2,42                      favorites: [WorkspaceFavorite(title: "localhost:3000", url: "http://localhost:3000"),43                                  WorkspaceFavorite(title: "localhost:8080", url: "http://localhost:8080")]),44        ]45    }46}4748struct WindowSnapshot: Codable, Equatable, Sendable {49    var tabs: [TabSnapshot] = []50    var selectedTabID: UUID?51    var groups: [TabGroup] = []52    var profileID: UUID?53    var activeWorkspaceID: UUID?54    var frame: String?55    var sidebarVisible: Bool = true56}5758struct SessionSnapshot: Codable, Equatable, Sendable {59    static let currentVersion = 160    var version: Int = SessionSnapshot.currentVersion61    var savedAt: Date = Date()62    var windows: [WindowSnapshot] = []6364    var tabCount: Int { windows.reduce(0) { $0 + $1.tabs.count } }65}6667struct NamedSession: Identifiable, Equatable, Sendable {68    var id: String { fileName }69    var name: String70    var fileName: String71    var savedAt: Date72    var tabCount: Int73}7475enum SessionLoadOutcome: Equatable, Sendable {76    case loaded(SessionSnapshot)77    /// The main file was unreadable; the previous good copy was used.78    case recoveredFromBackup(SessionSnapshot)79    case empty80    /// Both the main file and its backup were unreadable; they were moved aside.81    case corrupt82}8384/// Persists the open windows so they can be restored after a quit or a crash.85/// Writes are atomic and the previous file is kept as a backup, so a crash mid-write86/// or a damaged file never costs more than the last save.87final class SessionStore: Sendable {88    let directory: URL89    var currentURL: URL { directory.appendingPathComponent("session.json") }90    var backupURL: URL { directory.appendingPathComponent("session.backup.json") }91    var namedDirectory: URL { directory.appendingPathComponent("Saved", isDirectory: true) }9293    init(directory: URL) {94        self.directory = directory95        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)96    }9798    func save(_ snapshot: SessionSnapshot) throws {99        let fm = FileManager.default100        if fm.fileExists(atPath: currentURL.path), (try? JSONFile.read(SessionSnapshot.self, from: currentURL)) != nil {101            _ = try? fm.removeItem(at: backupURL)102            try? fm.copyItem(at: currentURL, to: backupURL)103        }104        try JSONFile.write(snapshot, to: currentURL)105    }106107    func load() -> SessionLoadOutcome {108        let fm = FileManager.default109        let hasMain = fm.fileExists(atPath: currentURL.path)110        if hasMain, let snapshot = try? JSONFile.read(SessionSnapshot.self, from: currentURL) {111            return .loaded(snapshot)112        }113        if let snapshot = try? JSONFile.read(SessionSnapshot.self, from: backupURL) {114            if hasMain { quarantine(currentURL) }115            return .recoveredFromBackup(snapshot)116        }117        if hasMain || fm.fileExists(atPath: backupURL.path) {118            quarantine(currentURL)119            quarantine(backupURL)120            return .corrupt121        }122        return .empty123    }124125    func clear() {126        try? FileManager.default.removeItem(at: currentURL)127        try? FileManager.default.removeItem(at: backupURL)128    }129130    private func quarantine(_ url: URL) {131        guard FileManager.default.fileExists(atPath: url.path) else { return }132        let aside = directory.appendingPathComponent(url.lastPathComponent + ".corrupt-\(Int(Date().timeIntervalSince1970))")133        try? FileManager.default.moveItem(at: url, to: aside)134    }135136    // MARK: Named sessions137138    private struct NamedFile: Codable {139        var name: String140        var snapshot: SessionSnapshot141    }142143    @discardableResult144    func saveNamed(_ name: String, snapshot: SessionSnapshot) throws -> NamedSession {145        let clean = name.trimmingCharacters(in: .whitespacesAndNewlines)146        let fileName = UUID().uuidString + ".json"147        try JSONFile.write(NamedFile(name: clean.isEmpty ? L("Untitled session") : clean, snapshot: snapshot),148                           to: namedDirectory.appendingPathComponent(fileName))149        return NamedSession(name: clean, fileName: fileName, savedAt: snapshot.savedAt, tabCount: snapshot.tabCount)150    }151152    func listNamed() -> [NamedSession] {153        let files = (try? FileManager.default.contentsOfDirectory(at: namedDirectory, includingPropertiesForKeys: nil)) ?? []154        return files.filter { $0.pathExtension == "json" }.compactMap { url in155            guard let file = try? JSONFile.read(NamedFile.self, from: url) else { return nil }156            return NamedSession(name: file.name, fileName: url.lastPathComponent, savedAt: file.snapshot.savedAt, tabCount: file.snapshot.tabCount)157        }.sorted { $0.savedAt > $1.savedAt }158    }159160    func loadNamed(_ session: NamedSession) -> SessionSnapshot? {161        (try? JSONFile.read(NamedFile.self, from: namedDirectory.appendingPathComponent(session.fileName)))?.snapshot162    }163164    func deleteNamed(_ session: NamedSession) {165        try? FileManager.default.removeItem(at: namedDirectory.appendingPathComponent(session.fileName))166    }167}168
Files main
Menu

Theme