SPB Git

Repository Public

PaneViews.swift 17.8 KB 383 lines swift

1import AppKit2import DesignSystem3import SwiftUI4import TerminalCore5import WorkspaceKit67/// Lays out the panes of the selected tab as floating cards according to its split tree.8///9/// Pane frames always snap: a terminal that changes size tells its shell (SIGWINCH), so a frame10/// animation would send dozens of resizes. What moves instead is the card itself (it fades and11/// scales in or out), the focus ring and the dividers.12struct PaneCanvasView: View {13    @Bindable var state: WindowState14    let model: AppModel15    /// Leave a margin under the cards (no status bar or search bar below).16    var bottomInset = false17    @Environment(\.chrome) private var chrome1819    var body: some View {20        let immersive = state.focusMode || state.isQuickTerminal21        let gap = immersive ? CGFloat(Metrics.paneGap) : CGFloat(Metrics.cardGap)22        let edge = immersive ? 0 : CGFloat(Metrics.cardGap)23        let radius = immersive ? 0 : CGFloat(Radius.l)24        GeometryReader { geometry in25            let bounds = CGRect(x: edge, y: 0, width: max(geometry.size.width - edge * 2, 1),26                                height: max(geometry.size.height - (bottomInset ? edge : 0), 1))27            ZStack(alignment: .topLeading) {28                if let tab = state.selectedTab {29                    let frames: [PaneID: CGRect] = tab.zoomedPane.map { [$0: bounds] } ?? tab.layout.frames(in: bounds, gap: gap)30                    ZStack(alignment: .topLeading) {31                        ForEach(tab.layout.panes.filter { frames[$0] != nil }, id: \.self) { pane in32                            let frame = frames[pane] ?? .zero33                            PaneView(pane: pane, tab: tab, state: state, model: model, radius: radius)34                                .frame(width: max(frame.width, 1), height: max(frame.height, 1))35                                .offset(x: frame.minX, y: frame.minY)36                                .snapGeometry()37                                .transition(chrome.motion.pop)38                        }39                        if tab.zoomedPane == nil {40                            ForEach(tab.layout.dividers(in: bounds, gap: gap), id: \.self) { handle in41                                DividerHandleView(handle: handle, state: state, model: model)42                            }43                        }44                    }45                    .frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading)46                    .animation(chrome.motion.smooth, value: tab.layout.panes)47                    .animation(chrome.motion.smooth, value: tab.zoomedPane)48                    .id(tab.id)49                    .transition(chrome.motion.transition(.opacity.combined(with: .scale(scale: 0.985))))50                }51            }52            .animation(chrome.motion.fade, value: state.selectedTabID)53            .onAppear { state.controller?.canvasBounds = bounds }54            .onChange(of: geometry.size) { _, _ in state.controller?.canvasBounds = bounds }55        }56    }57}5859struct DividerHandleView: View {60    let handle: DividerHandle61    let state: WindowState62    let model: AppModel63    @State private var lastTranslation: CGFloat = 064    @State private var hovering = false65    @State private var dragging = false66    @Environment(\.chrome) private var chrome6768    var body: some View {69        let horizontal = handle.axis == .horizontal70        let active = hovering || dragging71        ZStack {72            Color.clear73            // A short grabber in the gap between two cards.74            Capsule()75                .fill(model.palette(in: state).accent.opacity(active ? 0.9 : 0))76                .frame(width: horizontal ? 3 : min(44, handle.rect.width * 0.4), height: horizontal ? min(44, handle.rect.height * 0.4) : 3)77                .scaleEffect(dragging && !chrome.motion.reduced ? 1.15 : 1)78                .animation(chrome.motion.snappy, value: active)79        }80        .frame(width: handle.rect.width, height: handle.rect.height)81        .contentShape(Rectangle())82        .offset(x: handle.rect.minX, y: handle.rect.minY)83        .onHover { inside in84            guard inside != hovering else { return }85            hovering = inside86            if inside { (horizontal ? NSCursor.resizeLeftRight : NSCursor.resizeUpDown).push() } else { NSCursor.pop() }87        }88        // A divider can disappear while the pointer is on it (pane closed): give the cursor back.89        .onDisappear { if hovering { NSCursor.pop() } }90        .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .global)91            .onChanged { value in92                dragging = true93                let translation = horizontal ? value.translation.width : value.translation.height94                let delta = translation - lastTranslation95                lastTranslation = translation96                guard handle.parentLength > 0 else { return }97                state.mutateSelectedTab { $0.layout.resize(split: handle.splitID, dividerIndex: handle.index, by: Double(delta / handle.parentLength)) }98            }99            .onEnded { _ in100                dragging = false101                lastTranslation = 0102                model.scheduleAutosave()103            })104        .onTapGesture(count: 2) { model.equalizePanes(in: state) }105        .accessibilityLabel("Pane divider")106        .accessibilityHint("Drag to resize the panes, double-click to equalize")107    }108}109110/// One pane: a card with a header (title, host, status, actions) above the terminal.111struct PaneView: View {112    let pane: PaneID113    let tab: TabModel114    @Bindable var state: WindowState115    let model: AppModel116    var radius: CGFloat = 0117    @Environment(\.chrome) private var chrome118119    var body: some View {120        let palette = model.palette(for: pane)121        let _ = model.tick122        let session = model.session(for: pane)123        let focused = tab.focusedPane == pane124        let multiple = tab.panes.count > 1125        let broadcasting = state.broadcastTabs.contains(tab.id)126        let opacity = model.settings.backgroundOpacity127        // A single pane needs no header: the tab already carries its title and state.128        let showHeader = model.settings.showPaneHeaders && !state.presentationMode && multiple129        let lit = focused && multiple130        let shape = RoundedRectangle(cornerRadius: radius, style: .continuous)131        VStack(spacing: 0) {132            if showHeader {133                PaneHeaderView(pane: pane, tab: tab, state: state, model: model, palette: palette, focused: focused)134            }135            ZStack(alignment: .bottom) {136                TerminalHostView(pane: pane, model: model, cornerRadius: radius, roundsTop: !showHeader)137                if let note = model.paneNotes[pane] {138                    PaneNoteView(text: note, pane: pane, model: model)139                } else if let session, !session.status.isRunning, session.status != .notStarted {140                    PaneNoteView(text: session.status.label, pane: pane, model: model)141                }142            }143        }144        .background {145            // The text surface is opaque unless the user lowered the window opacity; the halo of146            // the focused card is drawn behind it, never over the text.147            shape.fill(palette.background.opacity(opacity))148                .shadow(color: opacity >= 1 && radius > 0 ? (lit ? palette.glow : palette.cardShadow) : .clear, radius: lit ? 9 : 4, y: lit ? 0 : 1)149                .animation(chrome.motion.snappy, value: lit)150        }151        .clipShape(shape)152        .overlay {153            shape.strokeBorder(broadcasting ? palette.warning : (lit ? palette.accent : palette.hairline),154                               lineWidth: broadcasting ? 2 : (lit ? 1.5 : 1))155                .animation(chrome.motion.snappy, value: lit)156                .animation(chrome.motion.snappy, value: broadcasting)157                .allowsHitTesting(false)158        }159    }160}161162struct PaneHeaderView: View {163    let pane: PaneID164    let tab: TabModel165    @Bindable var state: WindowState166    let model: AppModel167    let palette: Palette168    let focused: Bool169    @State private var hovering = false170    @Environment(\.chrome) private var chrome171172    var body: some View {173        let metrics = ChromeMetrics.metrics(for: model.settings.density)174        let session = model.session(for: pane)175        let descriptor = tab.descriptor(for: pane)176        let running = session?.status.isRunning ?? false177        let busy = session?.hasForegroundJob ?? false178        let completion = model.completions[pane]179        HStack(spacing: 6) {180            Image(systemName: icon(for: descriptor?.kind))181                .font(.system(size: TypeScale.caption, weight: .medium))182                .foregroundStyle(focused ? palette.accent : palette.secondary)183            Text(model.paneTitle(pane))184                .font(.system(size: TypeScale.footnote, weight: focused ? .semibold : .regular))185                .foregroundStyle(focused ? palette.text : palette.secondary)186                .lineLimit(1).truncationMode(.middle)187            if let role = descriptor?.role {188                Text(role).font(.system(size: TypeScale.micro, weight: .medium)).textCase(.uppercase)189                    .padding(.horizontal, 4).padding(.vertical, 1)190                    .background(Capsule().fill(palette.hover)).foregroundStyle(palette.secondary)191            }192            if let host = model.remoteHost(of: pane) {193                Label(host, systemImage: "network").font(.system(size: TypeScale.caption)).foregroundStyle(palette.accent).lineLimit(1)194            }195            Spacer(minLength: 4)196            if let completion {197                Label("\(completion.name) ended · \(Formatters.duration(completion.duration))", systemImage: "flag.checkered")198                    .font(.system(size: TypeScale.caption)).foregroundStyle(palette.accent).lineLimit(1)199                    .transition(chrome.motion.pop)200            } else if busy, let name = session?.foregroundProcessName {201                HStack(spacing: 4) {202                    StatusDot(activity: .busy, palette: palette)203                    Text(name).font(.system(size: TypeScale.caption)).lineLimit(1)204                }205                .foregroundStyle(palette.accent)206                .accessibilityLabel("Running \(name)")207            } else {208                Text(running ? (session?.foregroundProcessName ?? "shell") : (session?.status.label ?? ""))209                    .font(.system(size: TypeScale.caption)).foregroundStyle(running ? palette.secondary : palette.warning).lineLimit(1)210            }211            HStack(spacing: 0) {212                if tab.panes.count > 1 {213                    IconButton(systemName: tab.zoomedPane == pane ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right",214                               help: tab.zoomedPane == pane ? "Restore Panes" : "Zoom Pane", size: 9) {215                        model.focus(pane, in: state)216                        model.toggleZoom(in: state)217                    }218                }219                IconButton(systemName: "xmark", help: "Close Pane", size: 9) { model.closePane(pane, in: state) }220            }221            .opacity(hovering || focused ? 1 : 0)222        }223        .padding(.horizontal, 9)224        .frame(height: metrics.paneHeaderHeight)225        .background(palette.elevated.opacity(model.settings.backgroundOpacity))226        .overlay(alignment: .bottom) { Rectangle().fill(palette.hairline).frame(height: 1) }227        .contentShape(Rectangle())228        .onHover { hovering = $0 }229        .animation(chrome.motion.snappy, value: hovering)230        .animation(chrome.motion.snappy, value: focused)231        .animation(chrome.motion.smooth, value: completion?.id)232        .onTapGesture(count: 2) {233            model.focus(pane, in: state)234            model.toggleZoom(in: state)235        }236        .onTapGesture { model.focus(pane, in: state) }237        .draggable(PaneDrag.token(for: pane))238        .dropDestination(for: String.self) { items, _ in239            // Dropping a pane on another pane's header swaps the two.240            guard let dragged = items.first.flatMap(PaneDrag.pane(from:)), dragged != pane else { return false }241            if state.tabIndex(containing: dragged) == state.tabIndex(containing: pane) {242                model.swapPanes(dragged, pane, in: state)243            } else {244                model.movePane(dragged, to: .right, of: pane)245            }246            return true247        }248        .contextMenu {249            Button("Rename Session…") { state.sheet = .renamePane(pane, current: descriptor?.customTitle ?? model.paneTitle(pane)) }250            Button("Duplicate Session") { model.duplicatePane(pane, in: state) }251            Button("Restart Session") { model.restartSession(pane) }252            Divider()253            Button("Move Pane to New Tab") { model.movePaneToNewTab(pane, in: state) }.disabled(tab.panes.count < 2)254            Button("Move Pane to New Window") { model.detachPane(pane, from: state) }.disabled(state.isQuickTerminal)255            Divider()256            Button("Close Pane") { model.closePane(pane, in: state) }257        }258        .accessibilityElement(children: .combine)259        .accessibilityLabel("Pane \(model.paneTitle(pane)), \(running ? (busy ? "task running" : "idle") : "ended")")260    }261262    private func icon(for kind: SessionKind?) -> String {263        switch kind {264        case .ssh: return "network"265        case .command: return "sparkle"266        default: return "terminal"267        }268    }269}270271/// Message at the bottom of a pane whose process ended or failed, with the honest next steps.272struct PaneNoteView: View {273    let text: String274    let pane: PaneID275    let model: AppModel276277    var body: some View {278        let palette = model.palette279        let isSSH: Bool = { if case .ssh = model.descriptor(for: pane)?.kind { return true } else { return false } }()280        HStack(spacing: 8) {281            Image(systemName: "info.circle").foregroundStyle(palette.warning)282            Text(text).font(.system(size: 11)).lineLimit(3)283            Spacer(minLength: 6)284            if model.session(for: pane)?.status.isRunning == false {285                Button(isSSH ? "Reconnect" : "Restart") { model.restartSession(pane) }.controlSize(.small)286            }287            IconButton(systemName: "xmark", help: "Dismiss", size: 9) { model.paneNotes[pane] = nil }288                .opacity(model.paneNotes[pane] == nil ? 0 : 1)289        }290        .padding(.horizontal, 10).padding(.vertical, 6)291        .floatingSurface(RoundedRectangle(cornerRadius: Radius.m, style: .continuous), stroke: palette.hairline)292        .padding(6)293    }294}295296// MARK: Terminal hosting297298/// AppKit container that owns the frame of a session's terminal view. The session view is299/// re-parented here when a pane moves between tabs or windows; the process is never touched.300final class TerminalContainerView: NSView {301    var pane: PaneID?302    weak var model: AppModel?303    private weak var hosted: NSView?304    /// Rounds the corners of the card the terminal sits in (top corners only without a header).305    var corners: (radius: CGFloat, top: Bool) = (0, true) {306        didSet {307            guard corners != oldValue else { return }308            applyCorners()309        }310    }311312    private func applyCorners() {313        wantsLayer = true314        layer?.cornerRadius = corners.radius315        layer?.masksToBounds = corners.radius > 0316        // The view is not flipped: "min Y" corners are the bottom ones.317        layer?.maskedCorners = corners.top318            ? [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]319            : [.layerMinXMinYCorner, .layerMaxXMinYCorner]320    }321    static let inset = NSEdgeInsets(top: 2, left: 6, bottom: 2, right: 2)322323    func attach(_ view: NSView) {324        if view.superview !== self {325            view.removeFromSuperview()326            addSubview(view)327        }328        hosted = view329        needsLayout = true330        if window != nil, let pane { model?.claimFocusIfNeeded(pane) }331    }332333    private var contentFrame: NSRect {334        let i = TerminalContainerView.inset335        return NSRect(x: i.left, y: i.bottom, width: max(bounds.width - i.left - i.right, 1), height: max(bounds.height - i.top - i.bottom, 1))336    }337338    override func layout() {339        super.layout()340        guard let hosted, hosted.superview === self else { return }341        if hosted.frame != contentFrame { hosted.frame = contentFrame }342        // Start the process only once the terminal has its real size, so the shell never sees343        // a transient 80×24.344        if window != nil, bounds.width > 60, bounds.height > 30, let pane {345            model?.startIfNeeded(pane)346        }347    }348349    override func viewDidMoveToWindow() {350        super.viewDidMoveToWindow()351        guard window != nil, let hosted, hosted.superview === self else { return }352        // The terminal recomputes its grid only when its frame changes while it is in a window:353        // force one change so a re-parented view never stays blank.354        let target = contentFrame355        hosted.frame = NSRect(x: target.minX, y: target.minY, width: max(target.width - 1, 1), height: target.height)356        hosted.frame = target357        needsLayout = true358        if let pane { model?.claimFocusIfNeeded(pane) }359    }360}361362struct TerminalHostView: NSViewRepresentable {363    let pane: PaneID364    let model: AppModel365    var cornerRadius: CGFloat = 0366    var roundsTop = true367368    func makeNSView(context: Context) -> TerminalContainerView {369        let container = TerminalContainerView()370        container.pane = pane371        container.model = model372        container.corners = (cornerRadius, roundsTop)373        if let session = model.session(for: pane) { container.attach(session.view) }374        return container375    }376377    func updateNSView(_ container: TerminalContainerView, context: Context) {378        container.pane = pane379        container.corners = (cornerRadius, roundsTop)380        if let session = model.session(for: pane), session.view.superview !== container { container.attach(session.view) }381    }382}383
Files main
Menu

Theme