Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6179,11 +6179,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}

if matchShortcut(event: event, shortcut: KeyboardShortcutSettings.shortcut(for: .splitBrowserRight)) {
#if DEBUG
dlog("shortcut.action name=splitBrowserRight \(debugShortcutRouteSnapshot(event: event))")
#endif
_ = performBrowserSplitShortcut(direction: .right)
return true
}

if matchShortcut(event: event, shortcut: KeyboardShortcutSettings.shortcut(for: .splitBrowserDown)) {
#if DEBUG
dlog("shortcut.action name=splitBrowserDown \(debugShortcutRouteSnapshot(event: event))")
#endif
_ = performBrowserSplitShortcut(direction: .down)
return true
}
Expand Down Expand Up @@ -6697,7 +6703,38 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
func performBrowserSplitShortcut(direction: SplitDirection) -> Bool {
_ = synchronizeActiveMainWindowContext(preferredWindow: NSApp.keyWindow ?? NSApp.mainWindow)

guard let panelId = tabManager?.createBrowserSplit(direction: direction) else { return false }
#if DEBUG
let directionLabel: String
switch direction {
case .left: directionLabel = "left"
case .right: directionLabel = "right"
case .up: directionLabel = "up"
case .down: directionLabel = "down"
}
let selectedTabBefore = tabManager?.selectedTabId?.uuidString.prefix(5) ?? "nil"
let focusedPanelBefore = tabManager?.selectedWorkspace?.focusedPanelId?.uuidString.prefix(5) ?? "nil"
dlog(
"split.browser.shortcut pre dir=\(directionLabel) " +
"tab=\(selectedTabBefore) focusedPanel=\(focusedPanelBefore)"
)
#endif

guard let panelId = tabManager?.createBrowserSplit(direction: direction) else {
#if DEBUG
dlog("split.browser.shortcut failed dir=\(directionLabel)")
#endif
return false
}

#if DEBUG
let selectedTabAfter = tabManager?.selectedTabId?.uuidString.prefix(5) ?? "nil"
let focusedPanelAfter = tabManager?.selectedWorkspace?.focusedPanelId?.uuidString.prefix(5) ?? "nil"
dlog(
"split.browser.shortcut post dir=\(directionLabel) " +
"created=\(panelId.uuidString.prefix(5)) tab=\(selectedTabAfter) focusedPanel=\(focusedPanelAfter)"
)
#endif

_ = focusBrowserAddressBar(panelId: panelId)
return true
}
Expand Down
124 changes: 121 additions & 3 deletions Sources/GhosttyTerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1613,6 +1613,13 @@ final class TerminalSurface: Identifiable, ObservableObject {
private let maxPendingTextBytes = 1_048_576
private var backgroundSurfaceStartQueued = false
private var surfaceCallbackContext: Unmanaged<GhosttySurfaceCallbackContext>?
private enum PortalLifecycleState: String {
case live
case closing
case closed
}
private var portalLifecycleState: PortalLifecycleState = .live
private var portalLifecycleGeneration: UInt64 = 1
@Published var searchState: SearchState? = nil {
didSet {
if let searchState {
Expand Down Expand Up @@ -1672,6 +1679,52 @@ final class TerminalSurface: Identifiable, ObservableObject {
attachedView?.tabId = newTabId
surfaceView.tabId = newTabId
}

func portalBindingGeneration() -> UInt64 {
portalLifecycleGeneration
}

func portalBindingStateLabel() -> String {
portalLifecycleState.rawValue
}

func canAcceptPortalBinding(expectedSurfaceId: UUID?, expectedGeneration: UInt64?) -> Bool {
guard portalLifecycleState == .live else { return false }
if let expectedSurfaceId, expectedSurfaceId != id {
return false
}
if let expectedGeneration, expectedGeneration != portalLifecycleGeneration {
return false
}
return true
}

func beginPortalCloseLifecycle(reason: String) {
guard portalLifecycleState != .closed else { return }
guard portalLifecycleState != .closing else { return }
portalLifecycleState = .closing
portalLifecycleGeneration &+= 1
#if DEBUG
dlog(
"surface.lifecycle.close.begin surface=\(id.uuidString.prefix(5)) " +
"workspace=\(tabId.uuidString.prefix(5)) reason=\(reason) " +
"generation=\(portalLifecycleGeneration)"
)
#endif
}

private func markPortalLifecycleClosed(reason: String) {
guard portalLifecycleState != .closed else { return }
portalLifecycleState = .closed
portalLifecycleGeneration &+= 1
#if DEBUG
dlog(
"surface.lifecycle.close.sealed surface=\(id.uuidString.prefix(5)) " +
"workspace=\(tabId.uuidString.prefix(5)) reason=\(reason) " +
"generation=\(portalLifecycleGeneration)"
)
#endif
}
#if DEBUG
private static let surfaceLogPath = "/tmp/cmux-ghostty-surface.log"
private static let sizeLogPath = "/tmp/cmux-ghostty-size.log"
Expand Down Expand Up @@ -2288,6 +2341,8 @@ final class TerminalSurface: Identifiable, ObservableObject {
#endif

deinit {
markPortalLifecycleClosed(reason: "deinit")

let callbackContext = surfaceCallbackContext
surfaceCallbackContext = nil

Expand All @@ -2299,16 +2354,38 @@ final class TerminalSurface: Identifiable, ObservableObject {
surface = nil

guard let surfaceToFree else {
#if DEBUG
dlog(
"surface.lifecycle.deinit.skip surface=\(id.uuidString.prefix(5)) " +
"workspace=\(tabId.uuidString.prefix(5)) reason=noRuntimeSurface"
)
#endif
callbackContext?.release()
return
}

#if DEBUG
let surfaceToken = String(id.uuidString.prefix(5))
let workspaceToken = String(tabId.uuidString.prefix(5))
dlog(
"surface.lifecycle.deinit.begin surface=\(surfaceToken) " +
"workspace=\(workspaceToken) hasAttachedView=\(attachedView != nil ? 1 : 0) " +
"hostedInWindow=\(hostedView.window != nil ? 1 : 0)"
)
#endif

// Keep teardown asynchronous to avoid re-entrant close/deinit loops, but retain
// callback userdata until surface free completes so callbacks never dereference
// a deallocated view pointer.
Task { @MainActor in
ghostty_surface_free(surfaceToFree)
callbackContext?.release()
#if DEBUG
dlog(
"surface.lifecycle.deinit.end surface=\(surfaceToken) " +
"workspace=\(workspaceToken) freed=1"
)
#endif
}
}
}
Expand Down Expand Up @@ -3764,6 +3841,13 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {

deinit {
// Surface lifecycle is managed by TerminalSurface, not the view
#if DEBUG
dlog(
"surface.view.deinit view=\(Unmanaged.passUnretained(self).toOpaque()) " +
"surface=\(terminalSurface?.id.uuidString.prefix(5) ?? "nil") " +
"inWindow=\(window != nil ? 1 : 0) hasSuperview=\(superview != nil ? 1 : 0)"
)
#endif
if let eventMonitor {
NSEvent.removeMonitor(eventMonitor)
}
Expand Down Expand Up @@ -4111,6 +4195,25 @@ final class GhosttySurfaceScrollView: NSView {
}
#endif

func portalBindingGuardState() -> (surfaceId: UUID?, generation: UInt64?, state: String) {
guard let terminalSurface = surfaceView.terminalSurface else {
return (surfaceId: nil, generation: nil, state: "missingSurface")
}
return (
surfaceId: terminalSurface.id,
generation: terminalSurface.portalBindingGeneration(),
state: terminalSurface.portalBindingStateLabel()
)
}

func canAcceptPortalBinding(expectedSurfaceId: UUID?, expectedGeneration: UInt64?) -> Bool {
guard let terminalSurface = surfaceView.terminalSurface else { return false }
return terminalSurface.canAcceptPortalBinding(
expectedSurfaceId: expectedSurfaceId,
expectedGeneration: expectedGeneration
)
}

init(surfaceView: GhosttyNSView) {
self.surfaceView = surfaceView
backgroundView = NSView(frame: .zero)
Expand Down Expand Up @@ -4249,6 +4352,13 @@ final class GhosttySurfaceScrollView: NSView {
}

deinit {
#if DEBUG
dlog(
"surface.hosted.deinit surface=\(debugSurfaceId?.uuidString.prefix(5) ?? "nil") " +
"inWindow=\(window != nil ? 1 : 0) hasSuperview=\(superview != nil ? 1 : 0) " +
"hidden=\(isHidden ? 1 : 0) frame=\(String(format: "%.1fx%.1f", frame.width, frame.height))"
)
#endif
observers.forEach { NotificationCenter.default.removeObserver($0) }
windowObservers.forEach { NotificationCenter.default.removeObserver($0) }
cancelFocusRequest()
Expand Down Expand Up @@ -5660,6 +5770,8 @@ struct GhosttyTerminalView: NSViewRepresentable {
hostedView.setSearchOverlay(searchState: searchState)
hostedView.setFocusHandler { onFocus?(terminalSurface.id) }
hostedView.setTriggerFlashHandler(onTriggerFlash)
let portalExpectedSurfaceId = terminalSurface.id
let portalExpectedGeneration = terminalSurface.portalBindingGeneration()
let forwardedDropZone = isVisibleInUI ? paneDropZone : nil
#if DEBUG
if coordinator.lastPaneDropZone != paneDropZone {
Expand Down Expand Up @@ -5695,7 +5807,9 @@ struct GhosttyTerminalView: NSViewRepresentable {
hostedView: hostedView,
to: host,
visibleInUI: coordinator.desiredIsVisibleInUI,
zPriority: coordinator.desiredPortalZPriority
zPriority: coordinator.desiredPortalZPriority,
expectedSurfaceId: portalExpectedSurfaceId,
expectedGeneration: portalExpectedGeneration
)
coordinator.lastBoundHostId = ObjectIdentifier(host)
hostedView.setVisibleInUI(coordinator.desiredIsVisibleInUI)
Expand All @@ -5719,7 +5833,9 @@ struct GhosttyTerminalView: NSViewRepresentable {
hostedView: hostedView,
to: host,
visibleInUI: coordinator.desiredIsVisibleInUI,
zPriority: coordinator.desiredPortalZPriority
zPriority: coordinator.desiredPortalZPriority,
expectedSurfaceId: portalExpectedSurfaceId,
expectedGeneration: portalExpectedGeneration
)
coordinator.lastBoundHostId = ObjectIdentifier(host)
hostedView.setVisibleInUI(coordinator.desiredIsVisibleInUI)
Expand All @@ -5742,7 +5858,9 @@ struct GhosttyTerminalView: NSViewRepresentable {
hostedView: hostedView,
to: host,
visibleInUI: coordinator.desiredIsVisibleInUI,
zPriority: coordinator.desiredPortalZPriority
zPriority: coordinator.desiredPortalZPriority,
expectedSurfaceId: portalExpectedSurfaceId,
expectedGeneration: portalExpectedGeneration
)
coordinator.lastBoundHostId = hostId
}
Expand Down
19 changes: 19 additions & 0 deletions Sources/Panels/TerminalPanel.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import Combine
import AppKit
import Bonsplit

/// TerminalPanel wraps an existing TerminalSurface and conforms to the Panel protocol.
/// This allows TerminalSurface to be used within the bonsplit-based layout system.
Expand Down Expand Up @@ -139,9 +140,27 @@ final class TerminalPanel: Panel, ObservableObject {
// The surface will be cleaned up by its deinit
// Detach from the window portal on real close so stale hosted views
// cannot remain above browser panes after split close.
surface.beginPortalCloseLifecycle(reason: "panel.close")
#if DEBUG
let frame = String(format: "%.1fx%.1f", hostedView.frame.width, hostedView.frame.height)
let bounds = String(format: "%.1fx%.1f", hostedView.bounds.width, hostedView.bounds.height)
dlog(
"surface.panel.close.begin panel=\(id.uuidString.prefix(5)) " +
"workspace=\(workspaceId.uuidString.prefix(5)) runtimeSurface=\(surface.surface != nil ? 1 : 0) " +
"inWindow=\(hostedView.window != nil ? 1 : 0) hasSuperview=\(hostedView.superview != nil ? 1 : 0) " +
"hidden=\(hostedView.isHidden ? 1 : 0) frame=\(frame) bounds=\(bounds)"
)
#endif
unfocus()
hostedView.setVisibleInUI(false)
TerminalWindowPortalRegistry.detach(hostedView: hostedView)
#if DEBUG
dlog(
"surface.panel.close.end panel=\(id.uuidString.prefix(5)) " +
"inWindow=\(hostedView.window != nil ? 1 : 0) hasSuperview=\(hostedView.superview != nil ? 1 : 0) " +
"hidden=\(hostedView.isHidden ? 1 : 0)"
)
#endif
}

func requestViewReattach() {
Expand Down
Loading