SPB Git

Repository Public

WorkspaceStore.swift 9.1 KB 146 lines swift

1import Foundation2import WorkspaceCore34/// Persists `WorkspaceState` relationally (workspaces → windows → tabs → panes). Layout trees are5/// stored as JSON per tab because a tree is naturally hierarchical; everything else is columnar so6/// it can be queried and migrated.7public final class WorkspaceStore: Sendable {8    private let db: SQLiteDatabase9    private let encoder: JSONEncoder = {10        let e = JSONEncoder(); e.outputFormatting = [.sortedKeys]; return e11    }()12    private let decoder = JSONDecoder()1314    public init(database: SQLiteDatabase) {15        self.db = database16    }1718    public func save(_ workspace: WorkspaceState, markCurrent: Bool = true) throws {19        let wsID = workspace.id.rawValue.uuidString20        try db.transaction {21            try db.execute("""22                INSERT INTO workspaces(id, name, is_current, created_at, updated_at) VALUES(?,?,?,?,?)23                ON CONFLICT(id) DO UPDATE SET name=excluded.name, is_current=excluded.is_current, updated_at=excluded.updated_at24                """, [.text(wsID), .text(workspace.name), SQLiteValue(markCurrent), SQLiteValue(workspace.createdAt), SQLiteValue(workspace.updatedAt)])25            if markCurrent {26                try db.execute("UPDATE workspaces SET is_current=0 WHERE id<>?", [.text(wsID)])27            }28            // Replace the whole subtree; tables cascade from windows and panes.29            try db.execute("DELETE FROM windows WHERE workspace_id=?", [.text(wsID)])30            try db.execute("DELETE FROM panes WHERE workspace_id=?", [.text(wsID)])31            for (wi, window) in workspace.windows.enumerated() {32                let g = window.geometry33                try db.execute("""34                    INSERT INTO windows(id, workspace_id, position, selected_tab_id, role, frame_x, frame_y, frame_w, frame_h, display_id, display_name, is_fullscreen)35                    VALUES(?,?,?,?,?,?,?,?,?,?,?,?)36                    """, [.text(window.id.description), .text(wsID), .int(Int64(wi)), SQLiteValue(window.selectedTab?.description), SQLiteValue(window.role),37                          SQLiteValue(g.map { Double($0.frame.minX) }), SQLiteValue(g.map { Double($0.frame.minY) }),38                          SQLiteValue(g.map { Double($0.frame.width) }), SQLiteValue(g.map { Double($0.frame.height) }),39                          SQLiteValue(g?.displayID.map(Int.init)), SQLiteValue(g?.displayName), SQLiteValue(g?.isFullScreen ?? false)])40                for (ti, tab) in window.tabs.enumerated() {41                    let layout = try String(decoding: encoder.encode(tab.root), as: UTF8.self)42                    try db.execute("""43                        INSERT INTO tabs(id, window_id, position, custom_title, layout_json, focused_pane_id, maximized_pane_id) VALUES(?,?,?,?,?,?,?)44                        """, [.text(tab.id.description), .text(window.id.description), .int(Int64(ti)), SQLiteValue(tab.customTitle), .text(layout),45                              SQLiteValue(tab.focusedPane?.description), SQLiteValue(tab.maximizedPane?.description)])46                }47            }48            for pane in workspace.panes.values {49                let profile = try String(decoding: encoder.encode(pane.profile), as: UTF8.self)50                try db.execute("INSERT INTO panes(id, workspace_id, session_id, profile_json) VALUES(?,?,?,?)",51                               [.text(pane.id.description), .text(wsID), .text(pane.sessionID.description), .text(profile)])52            }53        }54    }5556    public func loadCurrent() throws -> WorkspaceState? {57        guard let row = try db.query("SELECT id FROM workspaces WHERE is_current=1 ORDER BY updated_at DESC LIMIT 1").first,58              let id = row.string("id"), let uuid = UUID(uuidString: id) else { return nil }59        return try load(WorkspaceID(rawValue: uuid))60    }6162    public func load(_ id: WorkspaceID) throws -> WorkspaceState? {63        let wsID = id.description64        guard let ws = try db.query("SELECT * FROM workspaces WHERE id=?", [.text(wsID)]).first else { return nil }65        var panes: [PaneID: PaneState] = [:]66        for row in try db.query("SELECT * FROM panes WHERE workspace_id=?", [.text(wsID)]) {67            guard let pid = row.string("id").flatMap(UUID.init(uuidString:)),68                  let sid = row.string("session_id").flatMap(UUID.init(uuidString:)),69                  let json = row.string("profile_json") else { continue }70            let profile = (try? decoder.decode(SessionProfile.self, from: Data(json.utf8))) ?? SessionProfile()71            let paneID = PaneID(rawValue: pid)72            panes[paneID] = PaneState(id: paneID, sessionID: SessionID(rawValue: sid), profile: profile)73        }74        var windows: [WindowState] = []75        for w in try db.query("SELECT * FROM windows WHERE workspace_id=? ORDER BY position", [.text(wsID)]) {76            guard let wid = w.string("id").flatMap(UUID.init(uuidString:)) else { continue }77            var tabs: [TabState] = []78            for t in try db.query("SELECT * FROM tabs WHERE window_id=? ORDER BY position", [.text(wid.uuidString)]) {79                guard let tid = t.string("id").flatMap(UUID.init(uuidString:)), let json = t.string("layout_json"),80                      let root = try? decoder.decode(LayoutNode.self, from: Data(json.utf8)) else { continue }81                // Drop leaves whose pane record is missing so a partially written row can't poison the layout.82                var cleaned: LayoutNode? = root83                for pane in root.paneIDs where panes[pane] == nil { cleaned = cleaned?.removing(pane) }84                guard let cleanedRoot = cleaned else { continue }85                let focused = t.string("focused_pane_id").flatMap(UUID.init(uuidString:)).map(PaneID.init(rawValue:))86                let maximized = t.string("maximized_pane_id").flatMap(UUID.init(uuidString:)).map(PaneID.init(rawValue:))87                tabs.append(TabState(id: TabID(rawValue: tid), customTitle: t.string("custom_title"), root: cleanedRoot,88                                     focusedPane: focused.flatMap { cleanedRoot.contains($0) ? $0 : nil },89                                     maximizedPane: maximized.flatMap { cleanedRoot.contains($0) ? $0 : nil }))90            }91            if tabs.isEmpty { continue }92            var geometry: WindowGeometry?93            if let x = w.double("frame_x"), let y = w.double("frame_y"), let wd = w.double("frame_w"), let h = w.double("frame_h") {94                geometry = WindowGeometry(frame: CGRect(x: x, y: y, width: wd, height: h), displayID: w.int("display_id").map(UInt32.init),95                                          displayName: w.string("display_name"), isFullScreen: w.bool("is_fullscreen"))96            }97            let selected = w.string("selected_tab_id").flatMap(UUID.init(uuidString:)).map(TabID.init(rawValue:))98            windows.append(WindowState(id: WindowID(rawValue: wid), tabs: tabs,99                                       selectedTab: selected.flatMap { s in tabs.contains { $0.id == s } ? s : nil },100                                       geometry: geometry, role: w.string("role")))101        }102        // Panes not referenced by any tab are orphans; drop them so the state is consistent.103        let referenced = Set(windows.flatMap { $0.tabs.flatMap(\.paneIDs) })104        panes = panes.filter { referenced.contains($0.key) }105        return WorkspaceState(id: id, name: ws.string("name") ?? "Workspace", windows: windows, panes: panes,106                              createdAt: ws.date("created_at") ?? Date(), updatedAt: ws.date("updated_at") ?? Date())107    }108109    public struct Summary: Sendable, Identifiable, Hashable {110        public let id: WorkspaceID111        public let name: String112        public let isCurrent: Bool113        public let updatedAt: Date114        public let windowCount: Int115        public let paneCount: Int116    }117118    public func list() throws -> [Summary] {119        try db.query("""120            SELECT w.id, w.name, w.is_current, w.updated_at,121                   (SELECT COUNT(*) FROM windows x WHERE x.workspace_id=w.id) AS windows,122                   (SELECT COUNT(*) FROM panes p WHERE p.workspace_id=w.id) AS panes123            FROM workspaces w ORDER BY w.updated_at DESC124            """).compactMap { row in125            guard let id = row.string("id").flatMap(UUID.init(uuidString:)) else { return nil }126            return Summary(id: WorkspaceID(rawValue: id), name: row.string("name") ?? "", isCurrent: row.bool("is_current"),127                           updatedAt: row.date("updated_at") ?? Date(), windowCount: row.int("windows") ?? 0, paneCount: row.int("panes") ?? 0)128        }129    }130131    public func delete(_ id: WorkspaceID) throws {132        try db.execute("DELETE FROM workspaces WHERE id=?", [.text(id.description)])133    }134135    public func rename(_ id: WorkspaceID, to name: String) throws {136        try db.execute("UPDATE workspaces SET name=?, updated_at=? WHERE id=?", [.text(name), SQLiteValue(Date()), .text(id.description)])137    }138139    public func setCurrent(_ id: WorkspaceID) throws {140        try db.transaction {141            try db.execute("UPDATE workspaces SET is_current=0")142            try db.execute("UPDATE workspaces SET is_current=1 WHERE id=?", [.text(id.description)])143        }144    }145}146
Files main
Menu

Theme