Repository Public
1import AppKit2import DesignSystem3import SwiftUI4import TerminalCore5import WorkspaceKit67/// Window that tells the model about focus changes and marks key events as user input.8final class SPWindow: NSWindow {9 var onFirstResponderChange: ((NSResponder?) -> Void)?10 /// Hosted tests place windows on simulated displays outside the real screen.11 var allowsOffscreenFrames = false1213 override func sendEvent(_ event: NSEvent) {14 if event.type == .keyDown {15 UserInputScope.run { super.sendEvent(event) }16 } else {17 super.sendEvent(event)18 }19 }2021 override func makeFirstResponder(_ responder: NSResponder?) -> Bool {22 let accepted = super.makeFirstResponder(responder)23 if accepted { onFirstResponderChange?(responder) }24 return accepted25 }2627 override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect {28 allowsOffscreenFrames ? frameRect : super.constrainFrameRect(frameRect, to: screen)29 }3031 override var canBecomeKey: Bool { true }32 override var canBecomeMain: Bool { true }33}3435@MainActor36final class WorkspaceWindowController: NSWindowController, NSWindowDelegate {37 let state: WindowState38 unowned let model: AppModel39 /// Bounds of the pane canvas, reported by the SwiftUI layout (used for directional focus).40 var canvasBounds = CGRect(x: 0, y: 0, width: 1000, height: 700)41 private(set) var frameBeforeFullScreen: CGRect?42 private var closingWithoutPrompt = false4344 init(state: WindowState, model: AppModel, frame: CGRect) {45 self.state = state46 self.model = model47 let window = SPWindow(contentRect: frame, styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],48 backing: .buffered, defer: false)49 window.allowsOffscreenFrames = !model.environment.showsWindows50 window.titlebarAppearsTransparent = true51 window.titleVisibility = .hidden52 window.isReleasedWhenClosed = false53 window.tabbingMode = .disallowed54 window.minSize = NSSize(width: 480, height: 300)55 window.collectionBehavior = [.fullScreenPrimary, .managed]56 window.isRestorable = false57 // An empty unified toolbar makes the system title bar as tall as the tab bar, so the native58 // traffic lights are vertically centred on the tabs.59 let toolbar = NSToolbar(identifier: "ai.spboucher.spterm.titlebar")60 toolbar.showsBaselineSeparator = false61 toolbar.allowsUserCustomization = false62 window.toolbar = toolbar63 window.setFrame(frame, display: false)64 super.init(window: window)65 window.delegate = self66 window.onFirstResponderChange = { [weak self] responder in67 guard let self, let view = responder as? NSView else { return }68 self.model.viewDidBecomeFirstResponder(view, in: self.state)69 }70 let root = WindowRootView(state: state, model: model)71 let hosting = NSHostingView(rootView: root)72 hosting.sizingOptions = []73 window.contentView = hosting74 window.setFrame(frame, display: false)75 applyAppearance()76 updateTitle()77 }7879 @available(*, unavailable)80 required init?(coder: NSCoder) { fatalError("not supported") }8182 func applyAppearance() {83 guard let window else { return }84 let theme = model.theme85 window.appearance = NSAppearance(named: theme.isDark ? .darkAqua : .aqua)86 let opacity = CGFloat(model.settings.backgroundOpacity)87 window.isOpaque = opacity >= 188 window.backgroundColor = theme.chromeBackground.nsColor.withAlphaComponent(opacity)89 window.hasShadow = true90 let style: NSWindow.ToolbarStyle = model.settings.density == .expanded ? .unified : .unifiedCompact91 if window.toolbarStyle != style {92 // Changing the toolbar style lets AppKit resize and re-constrain the window: keep the frame.93 let frame = window.frame94 window.toolbarStyle = style95 if window.frame != frame, !isFullScreen { window.setFrame(frame, display: true) }96 }97 measureTitleBar()98 }99100 /// Reports the real geometry of the system title bar to the SwiftUI tab bar.101 func measureTitleBar() {102 guard let window, !isFullScreen else { return }103 let height = window.frame.height - window.contentLayoutRect.height104 if height > 20, abs(state.titleBarHeight - height) > 0.5 { state.titleBarHeight = height }105 if let zoom = window.standardWindowButton(.zoomButton), let host = zoom.superview {106 let inset = host.convert(zoom.frame, to: nil).maxX + 10107 if inset > 40, abs(state.trafficLightInset - inset) > 0.5 { state.trafficLightInset = inset }108 }109 }110111 /// Focus mode hides the traffic lights with the rest of the chrome; they return with it.112 /// The whole system title bar view is faded, then hidden: AppKit re-applies the state of the113 /// individual buttons whenever the title bar lays out, but leaves their container alone.114 private(set) var trafficLightsVisible = true115 func syncTrafficLights() { setTrafficLights(visible: state.showsTitleBar) }116117 func setTrafficLights(visible: Bool) {118 guard visible != trafficLightsVisible, let window, let bar = window.standardWindowButton(.closeButton)?.superview else { return }119 trafficLightsVisible = visible120 if visible { bar.isHidden = false }121 NSAnimationContext.runAnimationGroup({ context in122 context.duration = model.motion.reduced ? 0 : 0.2123 bar.animator().alphaValue = visible ? 1 : 0124 }, completionHandler: { [weak self] in125 MainActor.assumeIsolated {126 guard let self, !self.trafficLightsVisible else { return }127 bar.isHidden = true128 }129 })130 }131132 /// The system title is hidden in the window but still drives Mission Control, the Window133 /// menu and VoiceOver.134 func updateTitle() {135 let title = state.selectedTab.map { model.tabTitle($0) } ?? "SP Term"136 if window?.title != title { window?.title = title }137 syncTrafficLights()138 }139140 func closeWithoutPrompt() {141 closingWithoutPrompt = true142 window?.close()143 }144145 var isFullScreen: Bool { window?.styleMask.contains(.fullScreen) ?? false }146147 // MARK: NSWindowDelegate148149 func windowShouldClose(_ sender: NSWindow) -> Bool {150 if closingWithoutPrompt { return true }151 model.closeWindow(state)152 return false153 }154155 func windowDidMove(_ notification: Notification) { model.scheduleAutosave() }156 func windowDidResize(_ notification: Notification) {157 measureTitleBar()158 model.scheduleAutosave()159 }160161 func windowDidBecomeKey(_ notification: Notification) {162 model.focusCurrentPane(in: state)163 }164165 func windowWillEnterFullScreen(_ notification: Notification) {166 frameBeforeFullScreen = window?.frame167 // In full screen the system shows its own title bar on demand; ours needs no toolbar under it.168 window?.toolbar?.isVisible = false169 state.isFullScreen = true170 }171172 func windowDidExitFullScreen(_ notification: Notification) {173 frameBeforeFullScreen = nil174 window?.toolbar?.isVisible = true175 state.isFullScreen = false176 model.windowDidLeaveFullScreen(state)177 measureTitleBar()178 model.scheduleAutosave()179 }180181 func windowDidChangeScreen(_ notification: Notification) { model.scheduleAutosave() }182}183