Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 10 additions & 11 deletions Sources/GhosttyTerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13386,18 +13386,17 @@ struct GhosttyTerminalView: NSViewRepresentable {

enum HostCallbackPortalGeometrySynchronizationAction<Window> {
case skip
case scheduleExternal(Window)
case synchronizeWithoutLayoutFlush(Window)
}

static func hostCallbackPortalGeometrySynchronizationAction<Window>(
window: Window?
) -> HostCallbackPortalGeometrySynchronizationAction<Window> {
// HostContainerView callbacks can fire while SwiftUI/AppKit is already
// rendering or laying out the representable. External AppKit resize
// observers own immediate live-resize flushing; host callbacks only
// schedule the portal owner.
// rendering or laying out the representable. Keep the immediate path,
// but forbid ancestor layout flushes from this callback.
guard let window else { return .skip }
return .scheduleExternal(window)
return .synchronizeWithoutLayoutFlush(window)
}

private static func synchronizePortalGeometry(
Expand All @@ -13407,14 +13406,14 @@ struct GhosttyTerminalView: NSViewRepresentable {
let geometryRevision = host.geometryRevision
guard coordinator.lastSynchronizedHostGeometryRevision != geometryRevision else { return }
coordinator.lastSynchronizedHostGeometryRevision = geometryRevision
// Avoid synchronizing the terminal portal while AppKit is still inside
// the current layout turn. Re-entrant syncs here can escalate from
// SwiftUI warnings to AppKit exceptions during CATransaction display
// link flushes.
guard case let .scheduleExternal(window) = hostCallbackPortalGeometrySynchronizationAction(
// Avoid forcing ancestor AppKit layout while SwiftUI is still inside
// the current update/layout turn. Reconcile the portal against the
// already-current host geometry so terminal content tracks resize
// without reopening the CATransaction display-link reentry path.
guard case .synchronizeWithoutLayoutFlush = hostCallbackPortalGeometrySynchronizationAction(
window: host.window
) else { return }
TerminalWindowPortalRegistry.scheduleExternalGeometrySynchronize(for: window)
TerminalWindowPortalRegistry.synchronizeForAnchor(host, syncLayout: false)
}

func makeNSView(context: Context) -> NSView {
Expand Down
112 changes: 77 additions & 35 deletions Sources/TerminalWindowPortal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -762,9 +762,7 @@ final class WindowTerminalPortal: NSObject {
}

fileprivate func scheduleExternalGeometrySynchronize() {
scheduleExternalGeometrySynchronize(
forceImmediate: TerminalWindowPortalRegistry.isInteractiveGeometryResizeActive
)
scheduleExternalGeometrySynchronize(forceImmediate: true)
}

fileprivate func scheduleExternalGeometrySynchronize(forceImmediate: Bool) {
Expand All @@ -778,11 +776,26 @@ final class WindowTerminalPortal: NSObject {
return
}
hasExternalGeometrySyncScheduled = true
let requiresSettledLayout = !(hostView.inLiveResize || window?.inLiveResize == true || forceImmediate)
DispatchQueue.main.async { [weak self] in
guard let self else { return }
let performSync = {
if self.externalGeometrySyncGeneration != generation {
var shouldFlushLatestNow = forceImmediate
if !shouldFlushLatestNow {
shouldFlushLatestNow = self.pendingExternalGeometrySyncRequiresImmediate
}
if !shouldFlushLatestNow {
shouldFlushLatestNow = self.hostView.inLiveResize
}
if !shouldFlushLatestNow {
shouldFlushLatestNow = self.window?.inLiveResize == true
}
if !shouldFlushLatestNow {
shouldFlushLatestNow = TerminalWindowPortalRegistry.isInteractiveGeometryResizeActive
}
// During sidebar/split drags, new geometry requests can arrive
// faster than this queued sync runs. Flush the latest visible
// frame instead of rescheduling behind the drag stream.
if self.externalGeometrySyncGeneration != generation, !shouldFlushLatestNow {
self.hasExternalGeometrySyncScheduled = false
let followUpRequiresImmediate = self.pendingExternalGeometrySyncRequiresImmediate
self.pendingExternalGeometrySyncRequiresImmediate = false
Expand All @@ -793,10 +806,23 @@ final class WindowTerminalPortal: NSObject {
self.pendingExternalGeometrySyncRequiresImmediate = false
self.synchronizeAllEntriesFromExternalGeometryChange()
}
if requiresSettledLayout {
DispatchQueue.main.async(execute: performSync)
} else {
var shouldPerformNow = forceImmediate
if !shouldPerformNow {
shouldPerformNow = self.pendingExternalGeometrySyncRequiresImmediate
}
if !shouldPerformNow {
shouldPerformNow = self.hostView.inLiveResize
}
if !shouldPerformNow {
shouldPerformNow = self.window?.inLiveResize == true
}
if !shouldPerformNow {
shouldPerformNow = TerminalWindowPortalRegistry.isInteractiveGeometryResizeActive
}
if shouldPerformNow {
performSync()
} else {
DispatchQueue.main.async(execute: performSync)
}
Comment on lines 781 to 826

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Flush predicate evaluated twice with state that can change between hops

The same 5-condition predicate (forceImmediate, pendingExternalGeometrySyncRequiresImmediate, hostView.inLiveResize, window?.inLiveResize, isInteractiveGeometryResizeActive) is evaluated once as shouldPerformNow (deciding whether to defer performSync to a second async hop) and again inside performSync as shouldFlushLatestNow (deciding whether to flush-latest or re-schedule when generation has advanced). When shouldPerformNow is false, the second evaluation happens one more event-loop turn later, at which point pendingExternalGeometrySyncRequiresImmediate may have changed. The result is that the outer decision ("don't flush immediately") can be silently overridden by the inner one — which is the intended behaviour for the generation-coalescing case, but the invariant is embedded implicitly rather than named. If one of the five conditions is ever updated in one location and not the other, the two halves will silently diverge.

File Used: .github/review-bot-rules/swift-architectural-rethink.md (source)

}
}
Expand Down Expand Up @@ -1199,9 +1225,7 @@ final class WindowTerminalPortal: NSObject {
}
// Keep inner scroll/surface geometry in sync with the seeded outer frame
// before the hosted view enters a window.
if !deferLayoutSynchronization {
hostedView.reconcileGeometryNow()
}
hostedView.reconcileGeometryNow()

if hostedView.superview !== hostView {
#if DEBUG
Expand Down Expand Up @@ -1229,30 +1253,36 @@ final class WindowTerminalPortal: NSObject {

if deferLayoutSynchronization {
// Bind calls from SwiftUI NSViewRepresentable update/layout callbacks
// must not force layout synchronously. Record the binding now and let
// the portal owner reconcile geometry after the current render turn.
scheduleExternalGeometrySynchronize(forceImmediate: false)
// must not force ancestor layout synchronously. Still reconcile the
// portal entry from already-current host geometry so resize/visibility
// does not lag until a later external observer turn.
synchronizeHostedView(withId: hostedId, syncLayout: false)
scheduleDeferredFullSynchronizeAll()
} else {
synchronizeHostedView(withId: hostedId)
scheduleDeferredFullSynchronizeAll()
}
Comment on lines 1253 to 1264

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 syncLayout: false and deferLayoutSynchronization now encode the same invariant at different call sites

The "don't trigger ancestor layoutSubtreeIfNeeded during a SwiftUI render turn" invariant is now split across two mechanisms: deferLayoutSynchronization (used in bindHostedView coming from NSViewRepresentable callbacks) and syncLayout: Bool (threaded through five method signatures for the synchronizePortalGeometry → synchronizeForAnchor path). These two branches are structurally identical except for syncLayout, meaning future changes to what "deferred bind" means must be applied to both the branch condition and the five downstream signatures. Per cmux-swift-architectural-rethink, naming a single predicate (e.g., a LayoutSyncPolicy enum) and routing both callers through it would make this invariant explicit and harder to miss.

File Used: .github/review-bot-rules/swift-architectural-rethink.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

pruneDeadEntries()
}

func synchronizeHostedViewForAnchor(_ anchorView: NSView) {
guard ensureInstalled() else { return }
synchronizeLayoutHierarchy()
func synchronizeHostedViewForAnchor(_ anchorView: NSView, syncLayout: Bool = true) {
guard ensureInstalled(syncLayout: syncLayout) else { return }
if syncLayout {
synchronizeLayoutHierarchy()
} else {
_ = synchronizeHostFrameToReference()
}
pruneDeadEntries()
let anchorId = ObjectIdentifier(anchorView)
let primaryHostedId = hostedByAnchorId[anchorId]
if let primaryHostedId {
synchronizeHostedView(withId: primaryHostedId)
synchronizeHostedView(withId: primaryHostedId, syncLayout: syncLayout)
}

// Failsafe: during aggressive divider drags/structural churn, one anchor can miss a
// geometry callback while another fires. Reconcile all mapped hosted views so no stale
// frame remains "stuck" onscreen until the next interaction.
synchronizeAllHostedViews(excluding: primaryHostedId)
synchronizeAllHostedViews(excluding: primaryHostedId, syncLayout: syncLayout)
reconcileVisibleHostedViewsAfterGeometrySync(reason: "portal.anchorGeometrySync")
scheduleDeferredFullSynchronizeAll()
}
Expand All @@ -1279,14 +1309,18 @@ final class WindowTerminalPortal: NSObject {
}
}

private func synchronizeAllHostedViews(excluding hostedIdToSkip: ObjectIdentifier?) {
guard ensureInstalled() else { return }
synchronizeLayoutHierarchy()
private func synchronizeAllHostedViews(excluding hostedIdToSkip: ObjectIdentifier?, syncLayout: Bool = true) {
guard ensureInstalled(syncLayout: syncLayout) else { return }
if syncLayout {
synchronizeLayoutHierarchy()
} else {
_ = synchronizeHostFrameToReference()
}
pruneDeadEntries()
let hostedIds = Array(entriesByHostedId.keys)
for hostedId in hostedIds {
if hostedId == hostedIdToSkip { continue }
synchronizeHostedView(withId: hostedId)
synchronizeHostedView(withId: hostedId, syncLayout: syncLayout)
}
}

Expand Down Expand Up @@ -1322,8 +1356,8 @@ final class WindowTerminalPortal: NSObject {
return true
}

private func synchronizeHostedView(withId hostedId: ObjectIdentifier) {
guard ensureInstalled() else { return }
private func synchronizeHostedView(withId hostedId: ObjectIdentifier, syncLayout: Bool = true) {
guard ensureInstalled(syncLayout: syncLayout) else { return }
guard var entry = entriesByHostedId[hostedId] else { return }
guard let hostedView = entry.hostedView else {
entriesByHostedId.removeValue(forKey: hostedId)
Expand Down Expand Up @@ -2036,14 +2070,14 @@ enum TerminalWindowPortalRegistry {
pruneHostedMappings(for: windowId, validHostedIds: nextPortal.hostedIds())
}

static func synchronizeForAnchor(_ anchorView: NSView) {
static func synchronizeForAnchor(_ anchorView: NSView, syncLayout: Bool = true) {
guard let window = anchorView.window else { return }
let portal = portal(for: window)
portal.synchronizeHostedViewForAnchor(anchorView)
let portal = portal(for: window, syncLayout: syncLayout)
portal.synchronizeHostedViewForAnchor(anchorView, syncLayout: syncLayout)
}

static func scheduleExternalGeometrySynchronize(for window: NSWindow) {
existingPortal(for: window)?.scheduleExternalGeometrySynchronize()
static func scheduleExternalGeometrySynchronize(for window: NSWindow, forceImmediate: Bool = true) {
existingPortal(for: window)?.scheduleExternalGeometrySynchronize(forceImmediate: forceImmediate)
}

static func beginInteractiveGeometryResize() {
Expand All @@ -2054,27 +2088,35 @@ enum TerminalWindowPortalRegistry {
interactiveGeometryResizeCount = max(0, interactiveGeometryResizeCount - 1)
}

static func scheduleExternalGeometrySynchronizeForAllWindows() {
static func scheduleExternalGeometrySynchronizeForAllWindows(forceImmediate: Bool = true) {
// Same latest-request-wins coalescing for callers that don't have a
// concrete window handle yet.
Self.externalGeometrySyncForAllWindowsGeneration &+= 1
let generation = Self.externalGeometrySyncForAllWindowsGeneration
guard !Self.hasPendingExternalGeometrySyncForAllWindows else { return }
Self.hasPendingExternalGeometrySyncForAllWindows = true
let isDragEvent = Self.isInteractiveGeometryResizeActive
let isDragEvent = forceImmediate || Self.isInteractiveGeometryResizeActive
DispatchQueue.main.async {
let performSync = {
if Self.externalGeometrySyncForAllWindowsGeneration != generation {
var shouldFlushLatestNow = isDragEvent
if !shouldFlushLatestNow {
shouldFlushLatestNow = Self.isInteractiveGeometryResizeActive
}
if Self.externalGeometrySyncForAllWindowsGeneration != generation, !shouldFlushLatestNow {
Self.hasPendingExternalGeometrySyncForAllWindows = false
Self.scheduleExternalGeometrySynchronizeForAllWindows()
Self.scheduleExternalGeometrySynchronizeForAllWindows(forceImmediate: forceImmediate)
return
}
Self.hasPendingExternalGeometrySyncForAllWindows = false
for portal in Self.portalsByWindowId.values {
portal.synchronizeAllEntriesFromExternalGeometryChange()
}
}
if isDragEvent {
var shouldPerformNow = isDragEvent
if !shouldPerformNow {
shouldPerformNow = Self.isInteractiveGeometryResizeActive
}
if shouldPerformNow {
performSync()
} else {
DispatchQueue.main.async(execute: performSync)
Expand Down
8 changes: 4 additions & 4 deletions cmuxTests/GhosttyTerminalViewVisibilityPolicyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,18 @@ final class GhosttyTerminalViewVisibilityPolicyTests: XCTestCase {
)
}

func testSwiftUIHostGeometryCallbackSchedulesExternalSynchronization() {
func testSwiftUIHostGeometryCallbackUsesImmediateSyncWithoutLayoutFlush() {
switch GhosttyTerminalView.hostCallbackPortalGeometrySynchronizationAction(window: 3873) {
case .scheduleExternal(let window):
case .synchronizeWithoutLayoutFlush(let window):
XCTAssertEqual(window, 3873)
case .skip:
XCTFail("Window-attached host callbacks should schedule deferred portal synchronization")
XCTFail("Window-attached host callbacks should immediately reconcile portal geometry without layout flushes")
}
}

func testSwiftUIHostGeometryCallbackSkipsWithoutWindow() {
switch GhosttyTerminalView.hostCallbackPortalGeometrySynchronizationAction(window: Optional<Int>.none) {
case .scheduleExternal:
case .synchronizeWithoutLayoutFlush:
XCTFail("Detached host callbacks must not synchronize terminal portal geometry")
case .skip:
break
Expand Down
Loading