SPB Git

Repository Public

WorkspaceModels.swift 9.8 KB 237 lines swift

1import CoreGraphics2import Foundation34/// What runs inside a pane. Only launch *metadata* is stored: a restored workspace starts new5/// processes, it never pretends to resurrect old ones.6public enum SessionKind: Codable, Sendable, Hashable {7    /// Interactive local shell; `nil` means the user's default shell.8    case localShell(path: String?)9    /// OpenSSH connection to a host alias / profile id handled by SSHKit.10    case ssh(hostAlias: String)11    /// An installed command-line program (agent CLI, tmux attach, …) run through the login shell.12    case command(line: String)13}1415/// Persistent description of a pane.16public struct PaneDescriptor: Codable, Sendable, Hashable, Identifiable {17    public var id: PaneID18    public var kind: SessionKind19    /// User-chosen title; `nil` shows the title reported by the terminal.20    public var customTitle: String?21    /// Directory the session starts in (last known cwd when the workspace was saved).22    public var workingDirectory: String?23    /// Logical role used by presets ("editor", "tests", "logs", "agent"…), shown as a badge.24    public var role: String?25    /// Part of the broadcast-input group of its tab.26    public var receivesBroadcast: Bool2728    public init(id: PaneID = PaneID(), kind: SessionKind = .localShell(path: nil), customTitle: String? = nil,29                workingDirectory: String? = nil, role: String? = nil, receivesBroadcast: Bool = false) {30        self.id = id31        self.kind = kind32        self.customTitle = customTitle33        self.workingDirectory = workingDirectory34        self.role = role35        self.receivesBroadcast = receivesBroadcast36    }3738    public init(from decoder: Decoder) throws {39        let c = try decoder.container(keyedBy: CodingKeys.self)40        id = try c.decode(PaneID.self, forKey: .id)41        kind = try c.decodeIfPresent(SessionKind.self, forKey: .kind) ?? .localShell(path: nil)42        customTitle = try c.decodeIfPresent(String.self, forKey: .customTitle)43        workingDirectory = try c.decodeIfPresent(String.self, forKey: .workingDirectory)44        role = try c.decodeIfPresent(String.self, forKey: .role)45        receivesBroadcast = try c.decodeIfPresent(Bool.self, forKey: .receivesBroadcast) ?? false46    }47}4849/// A tab: a split tree plus the descriptors of its panes.50public struct TabModel: Codable, Sendable, Hashable, Identifiable {51    public var id: TabID52    public var customTitle: String?53    public var layout: LayoutNode54    public var panes: [PaneDescriptor]55    public var focusedPane: PaneID?56    /// Pane temporarily shown full-tab; the layout itself is untouched.57    public var zoomedPane: PaneID?5859    public init(id: TabID = TabID(), customTitle: String? = nil, layout: LayoutNode, panes: [PaneDescriptor],60                focusedPane: PaneID? = nil, zoomedPane: PaneID? = nil) {61        self.id = id62        self.customTitle = customTitle63        self.layout = layout64        self.panes = panes65        self.focusedPane = focusedPane ?? layout.panes.first66        self.zoomedPane = zoomedPane67    }6869    /// A tab holding a single pane.70    public init(single pane: PaneDescriptor, customTitle: String? = nil) {71        self.init(customTitle: customTitle, layout: .pane(pane.id), panes: [pane], focusedPane: pane.id)72    }7374    public static func == (lhs: TabModel, rhs: TabModel) -> Bool {75        lhs.id == rhs.id && lhs.customTitle == rhs.customTitle && lhs.layout == rhs.layout76            && lhs.panes == rhs.panes && lhs.focusedPane == rhs.focusedPane && lhs.zoomedPane == rhs.zoomedPane77    }78    public func hash(into hasher: inout Hasher) { hasher.combine(id) }7980    public func descriptor(for pane: PaneID) -> PaneDescriptor? { panes.first { $0.id == pane } }8182    public mutating func update(_ pane: PaneID, _ change: (inout PaneDescriptor) -> Void) {83        guard let index = panes.firstIndex(where: { $0.id == pane }) else { return }84        change(&panes[index])85    }8687    /// Adds `descriptor` next to `target`. Returns `false` if `target` is unknown.88    @discardableResult89    public mutating func split(_ target: PaneID, axis: SplitAxis, adding descriptor: PaneDescriptor, before: Bool = false) -> Bool {90        guard layout.split(target, axis: axis, newPane: descriptor.id, before: before) else { return false }91        panes.append(descriptor)92        focusedPane = descriptor.id93        zoomedPane = nil94        return true95    }9697    /// Removes a pane and returns its descriptor. Returns `nil` when the pane is unknown.98    /// When the last pane is removed the tab becomes empty (`isEmpty`) and should be closed.99    @discardableResult100    public mutating func remove(_ pane: PaneID) -> PaneDescriptor? {101        guard let index = panes.firstIndex(where: { $0.id == pane }) else { return nil }102        let order = layout.panes103        let position = order.firstIndex(of: pane) ?? 0104        let removed = panes.remove(at: index)105        if let remaining = layout.removing(pane) {106            layout = remaining107            if focusedPane == pane {108                let next = layout.panes109                focusedPane = next.isEmpty ? nil : next[min(position, next.count - 1)]110            }111        } else {112            focusedPane = nil113        }114        if zoomedPane == pane { zoomedPane = nil }115        return removed116    }117118    public var isEmpty: Bool { panes.isEmpty }119120    /// Layout and descriptors agree and the tree is well formed.121    public var isConsistent: Bool {122        layout.isWellFormed && Set(layout.panes) == Set(panes.map(\.id)) && panes.count == layout.paneCount123            && (focusedPane.map { layout.contains($0) } ?? panes.isEmpty)124            && (zoomedPane.map { layout.contains($0) } ?? true)125    }126127    /// Repairs a tab decoded from disk (unknown panes, dangling focus) instead of failing to restore.128    public mutating func repair() {129        let known = Set(panes.map(\.id))130        var seen = Set<PaneID>()131        var tree: LayoutNode? = layout132        for pane in layout.panes where !known.contains(pane) || !seen.insert(pane).inserted {133            tree = tree?.removing(pane)134        }135        if let tree {136            layout = tree.normalized()137            let inTree = Set(layout.panes)138            panes.removeAll { !inTree.contains($0.id) }139        } else if let first = panes.first {140            layout = .pane(first.id)141            panes = [first]142        }143        if focusedPane.map({ !layout.contains($0) }) ?? true { focusedPane = layout.panes.first }144        if zoomedPane.map({ !layout.contains($0) }) ?? false { zoomedPane = nil }145    }146}147148/// Identity of the display a window was on when it was saved. Display ids are not stable across149/// reboots or cable changes, so name and geometry are kept as well for matching.150public struct ScreenReference: Codable, Sendable, Hashable {151    public var displayID: UInt32152    public var name: String153    public var frame: CGRect154    public var isMain: Bool155156    public init(displayID: UInt32, name: String, frame: CGRect, isMain: Bool) {157        self.displayID = displayID158        self.name = name159        self.frame = frame160        self.isMain = isMain161    }162}163164/// A window: ordered tabs, its frame in global screen coordinates and the display it lived on.165public struct WindowModel: Codable, Sendable, Hashable, Identifiable {166    public var id: WindowID167    public var tabs: [TabModel]168    public var selectedTab: TabID?169    /// Frame in AppKit global coordinates (origin bottom-left of the main display).170    public var frame: CGRect?171    public var screen: ScreenReference?172    public var isFullScreen: Bool173    /// Logical slot used by multi-monitor presets (0 = primary display, 1 = second display…).174    public var screenSlot: Int?175176    public init(id: WindowID = WindowID(), tabs: [TabModel], selectedTab: TabID? = nil, frame: CGRect? = nil,177                screen: ScreenReference? = nil, isFullScreen: Bool = false, screenSlot: Int? = nil) {178        self.id = id179        self.tabs = tabs180        self.selectedTab = selectedTab ?? tabs.first?.id181        self.frame = frame182        self.screen = screen183        self.isFullScreen = isFullScreen184        self.screenSlot = screenSlot185    }186187    public var paneCount: Int { tabs.reduce(0) { $0 + $1.panes.count } }188}189190/// A saved workspace: the logical arrangement of windows, tabs and panes.191public struct WorkspaceSnapshot: Codable, Sendable, Hashable, Identifiable {192    public var id: UUID193    public var name: String194    public var windows: [WindowModel]195    public var savedAt: Date196197    public init(id: UUID = UUID(), name: String, windows: [WindowModel], savedAt: Date = Date()) {198        self.id = id199        self.name = name200        self.windows = windows201        self.savedAt = savedAt202    }203204    public var paneCount: Int { windows.reduce(0) { $0 + $1.paneCount } }205206    /// Fresh identities for every window, tab and pane, so a saved workspace can be opened207    /// several times side by side without id collisions.208    public func instantiated() -> WorkspaceSnapshot {209        var copy = self210        copy.id = UUID()211        copy.windows = windows.map { window in212            var w = window213            w.id = WindowID()214            var selected: TabID?215            w.tabs = window.tabs.map { tab in216                var t = tab217                t.id = TabID()218                if tab.id == window.selectedTab { selected = t.id }219                var mapping: [PaneID: PaneID] = [:]220                t.panes = tab.panes.map { pane in221                    var p = pane222                    p.id = PaneID()223                    mapping[pane.id] = p.id224                    return p225                }226                for (old, new) in mapping { t.layout.replace(old, with: new) }227                t.focusedPane = tab.focusedPane.flatMap { mapping[$0] }228                t.zoomedPane = tab.zoomedPane.flatMap { mapping[$0] }229                return t230            }231            w.selectedTab = selected ?? w.tabs.first?.id232            return w233        }234        return copy235    }236}237
Files main
Menu

Theme