Files
helder/Sources/HelderUI/Shell/WindowBridge.swift
T
2026-10-30 11:27:44 +01:00

370 lines
16 KiB
Swift

import AppKit
import SwiftTerm
import SwiftUI
/// Reaches the hosting NSWindow for what SwiftUI cannot do: title bar geometry, the key router and window events.
struct WindowBridge: NSViewRepresentable {
let model: WorkspaceModel
/// Passed as values so a project switch re-runs `updateNSView`, which renames the window and the app.
let title: String
let hasProject: Bool
func makeCoordinator() -> WindowCoordinator {
WindowCoordinator(model: model)
}
func makeNSView(context: Context) -> BridgeView {
let view = BridgeView()
view.coordinator = context.coordinator
return view
}
func updateNSView(_ view: BridgeView, context: Context) {
context.coordinator.updateTitle(title, hasProject: hasProject)
context.coordinator.guardClose()
}
static func dismantleNSView(_ view: BridgeView, coordinator: WindowCoordinator) {
coordinator.detach()
}
final class BridgeView: NSView {
weak var coordinator: WindowCoordinator?
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let window { coordinator?.attach(to: window) }
}
}
}
@MainActor
final class WindowCoordinator: NSObject {
let model: WorkspaceModel
private weak var window: NSWindow?
private var monitors: [Any] = []
private var observers: [NSObjectProtocol] = []
private let closeGuard = WindowCloseGuard()
/// Set once the unsaved prompt said yes, so the second close goes through.
private var closeApproved = false
private var isAskingToClose = false
init(model: WorkspaceModel) {
self.model = model
}
func attach(to window: NSWindow) {
guard self.window !== window else { return }
detach()
self.window = window
configure(window)
installMonitors()
observe(window)
closeGuard.shouldClose = { [weak self] window in self?.shouldClose(window) ?? true }
guardClose()
WorkspaceRegistry.register(model, window: window)
model.hooks.closeWindow = { [weak window] in window?.performClose(nil) }
layoutTrafficLights()
}
/// Puts the close guard in front of SwiftUI's window delegate; SwiftUI may set its own again later.
func guardClose() {
guard let window, window.delegate !== closeGuard else { return }
closeGuard.original = window.delegate
window.delegate = closeGuard
}
/// The first close only asks: unsaved files prompt, the session is written, then the window closes.
private func shouldClose(_ window: NSWindow) -> Bool {
if closeApproved { return true }
guard !isAskingToClose else { return false }
isAskingToClose = true
Task { @MainActor [weak self, weak window] in
guard let self else { return }
let approved = await self.model.prepareToClose()
self.isAskingToClose = false
guard approved, let window else { return }
self.closeApproved = true
window.close()
}
return false
}
func detach() {
monitors.forEach(NSEvent.removeMonitor)
monitors = []
observers.forEach(NotificationCenter.default.removeObserver)
observers = []
}
/// The launcher keeps the app's own name.
func updateTitle(_ title: String, hasProject: Bool) {
window?.title = title
AppName.set(hasProject ? title : AppName.standard)
}
private func configure(_ window: NSWindow) {
window.title = model.title
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.styleMask.insert(.fullSizeContentView)
window.isMovableByWindowBackground = false
window.backgroundColor = NSColor(hex: 0x101720)
window.appearance = NSAppearance(named: .darkAqua)
window.minSize = Metrics.minimumWindow
window.tabbingMode = .disallowed
// A restored window would be a second project in this process.
window.isRestorable = false
if let content = window.contentView { PointerPolicy.claimCursorUpdates(of: content) }
}
// MARK: Traffic lights
/// Places the traffic lights at (14, 12) and grows the title-bar container to match, so the whole strip drags the window.
/// AppKit resets both on resize and full-screen changes, hence the repeat calls.
func layoutTrafficLights() {
guard let window,
let close = window.standardWindowButton(.closeButton),
let zoom = window.standardWindowButton(.zoomButton),
let container = close.superview?.superview else { return }
let buttons = [close, window.standardWindowButton(.miniaturizeButton), zoom].compactMap { $0 }
let spacing = zoom.frame.minX - (window.standardWindowButton(.miniaturizeButton)?.frame.maxX ?? close.frame.maxX)
let origin = Metrics.trafficLightOrigin
var frame = container.frame
frame.size.height = close.frame.height + origin.y * 2
frame.origin.y = window.frame.height - frame.height
container.frame = frame
for (index, button) in buttons.enumerated() {
button.setFrameOrigin(NSPoint(x: origin.x + CGFloat(index) * (button.frame.width + spacing),
y: (frame.height - button.frame.height) / 2))
}
}
private func observe(_ window: NSWindow) {
let center = NotificationCenter.default
let relayout: [Notification.Name] = [NSWindow.didResizeNotification, NSWindow.didEndLiveResizeNotification,
NSWindow.didExitFullScreenNotification, NSWindow.didBecomeKeyNotification]
for name in relayout {
observers.append(center.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.layoutTrafficLights() }
})
}
observers.append(center.addObserver(forName: NSWindow.willEnterFullScreenNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.layout.isFullScreen = true }
})
observers.append(center.addObserver(forName: NSWindow.didExitFullScreenNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.layout.isFullScreen = false }
})
observers.append(center.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated { self?.model.windowDidResignKey() }
})
observers.append(center.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
WorkspaceRegistry.becameKey(self.model)
self.model.windowDidBecomeKey()
}
})
observers.append(center.addObserver(forName: NSWindow.willCloseNotification, object: window, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self else { return }
WorkspaceRegistry.unregister(self.model)
if WorkspaceRegistry.models.isEmpty { AppName.set(AppName.standard) }
self.model.windowWillClose()
self.detach()
}
})
}
// MARK: Keyboard and pointer
private func installMonitors() {
if let keys = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: { [weak self] event in
let consumed = MainActor.assumeIsolated { self?.handleKey(event) ?? false }
return consumed ? nil : event
}) { monitors.append(keys) }
if let mouse = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown], handler: { [weak self] event in
MainActor.assumeIsolated { self?.handleMouseDown(event) }
return event
}) { monitors.append(mouse) }
}
/// Returns true when the key ran a command and must not reach the responder chain.
private func handleKey(_ event: NSEvent) -> Bool {
guard let window, event.window === window, window.attachedSheet == nil else { return false }
switch KeyRouter.route(KeyPress(event), context(in: window)) {
case .pass:
return false
case let .perform(command):
model.perform(command)
if case let .focus(panel) = command { takeFocus(for: panel, in: window) }
if case .focusNeighbour = command, let panel = model.layout.activePanel { takeFocus(for: panel, in: window) }
return true
}
}
/// Source Control and Explorer have no text view to focus, so they hold the keyboard by clearing first responder.
private func takeFocus(for panel: Panel, in window: NSWindow) {
if panel == .sourceControl || panel == .explorer { window.makeFirstResponder(nil) }
}
private func handleMouseDown(_ event: NSEvent) {
guard let window, event.window === window, model.root != nil, !model.overlay.isPresented else { return }
let point = event.locationInWindow
let height = window.contentView?.bounds.height ?? window.frame.height
guard height - point.y > Metrics.titleBar, point.y > Metrics.statusBar else { return }
guard let panel = model.layout.panel(atX: point.x, splitterMargin: 4) else { return }
model.pointerFocused(panel)
guard panel == .sourceControl || panel == .explorer else { return }
// A row click pulls the keyboard out of a text view in another column; otherwise typing lands there.
DispatchQueue.main.async { [weak self, weak window] in
guard let self, let window, let view = window.firstResponder as? NSView,
view is NSText || view is TerminalView else { return }
if self.column(of: view) != panel { window.makeFirstResponder(nil) }
}
}
private func column(of view: NSView) -> Panel? {
let frame = view.convert(view.visibleRect, to: nil)
return model.layout.panel(atX: frame.midX)
}
private func context(in window: NSWindow) -> KeyContext {
let responder = window.firstResponder
var owner = KeyboardOwner.workspace
var hasSelection = false
var editorSelection: TextSelectionInfo?
var seed = ""
if let text = responder as? NSTextView {
let column = column(of: text)
owner = .text(in: column)
let range = text.selectedRange()
hasSelection = range.length > 0
if hasSelection {
let string = text.string as NSString
let selected = string.substring(with: range)
seed = selected.split(separator: "\n", omittingEmptySubsequences: false).first.map(String.init)?
.trimmingCharacters(in: .whitespaces) ?? ""
if column == .editor {
editorSelection = TextSelectionInfo(text: selected, startLine: Self.line(at: range.location, in: string),
endLine: Self.line(at: range.location + range.length - 1, in: string))
}
}
} else if let terminal = responder as? TerminalView {
owner = .terminal
hasSelection = terminal.selectionActive
} else if let canvas = responder as? DiffCanvasView {
hasSelection = canvas.hasSelection
}
let editor = model.editor
let lineSelection = editor.flatMap { editor in
editor.selection.flatMap { $0.path == editor.activePath && $0.start != $0.end ? $0 : nil }
}
return KeyContext(
hasProject: model.root != nil,
overlay: OverlayKind(model.overlay.current, diffBusy: editor?.diffOverlayBusy ?? false),
owner: owner,
hasTextSelection: hasSelection,
editorTextSelection: editorSelection,
hasEditorLineSelection: lineSelection != nil,
activePanel: model.layout.activePanel,
focusZone: model.layout.focusZone,
recentFileCount: editor?.history.count ?? 0,
searchSeed: seed
)
}
private static func line(at location: Int, in string: NSString) -> Int {
let end = min(max(location, 0), string.length)
var line = 1
var index = 0
while index < end {
let range = string.range(of: "\n", options: [], range: NSRange(location: index, length: end - index))
guard range.location != NSNotFound else { break }
line += 1
index = range.location + 1
}
return line
}
}
extension KeyPress {
/// Reads `.` by key code, so ⌘. works on every keyboard layout.
init(_ event: NSEvent) {
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let key: Key
switch event.keyCode {
case 126: key = .up
case 125: key = .down
case 123: key = .left
case 124: key = .right
case 36, 76: key = .enter
case 53: key = .escape
case 47: key = .character(".")
default:
let typed = flags.contains(.command) ? event.charactersIgnoringModifiers : event.characters
key = typed.flatMap { $0.isEmpty ? nil : Key.character($0.lowercased()) } ?? .other
}
self.init(key, command: flags.contains(.command), shift: flags.contains(.shift),
option: flags.contains(.option), control: flags.contains(.control))
}
}
/// Stands in as the window's delegate to ask before a close, and hands every other message to SwiftUI's delegate.
final class WindowCloseGuard: NSObject, NSWindowDelegate {
weak var original: NSWindowDelegate?
var shouldClose: @MainActor (NSWindow) -> Bool = { _ in true }
override func responds(to selector: Selector!) -> Bool {
super.responds(to: selector) || original?.responds(to: selector) == true
}
override func forwardingTarget(for selector: Selector!) -> Any? {
original?.responds(to: selector) == true ? original : nil
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
let allowed = MainActor.assumeIsolated { shouldClose(sender) }
guard allowed else { return false }
return original?.windowShouldClose?(sender) ?? true
}
}
/// Every open workspace window, for ⌘Q and the Dock menu.
@MainActor
enum WorkspaceRegistry {
private struct Entry {
weak var model: WorkspaceModel?
weak var window: NSWindow?
}
private static var entries: [Entry] = []
private static weak var lastKey: WorkspaceModel?
static var models: [WorkspaceModel] { entries.compactMap(\.model) }
static func register(_ model: WorkspaceModel, window: NSWindow) {
entries.removeAll { $0.model == nil || $0.model === model }
entries.append(Entry(model: model, window: window))
}
static func unregister(_ model: WorkspaceModel) {
entries.removeAll { $0.model == nil || $0.model === model }
if lastKey === model { lastKey = nil }
}
static func model(for window: NSWindow) -> WorkspaceModel? {
entries.first { $0.window === window }?.model
}
static func becameKey(_ model: WorkspaceModel) {
lastKey = model
}
/// The key window's workspace, else the one that was key last.
static var current: WorkspaceModel? {
if let key = NSApp.keyWindow, let entry = entries.first(where: { $0.window === key }) { return entry.model }
return lastKey
}
}