Skip to content
6 changes: 2 additions & 4 deletions Sources/App/SessionSnapshotDebugBenchmark.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@ enum SessionSnapshotDebugBenchmark {
includeScrollback: Bool,
persist: Bool,
buildSnapshot: (Bool) -> AppSessionSnapshot?,
persistedGeometryData: (AppSessionSnapshot?) -> Data?,
persistSnapshot: (AppSessionSnapshot?, Data?) -> Void
persistSnapshot: (AppSessionSnapshot?) -> Void
) -> [String: Any] {
let buildStart = ProcessInfo.processInfo.systemUptime
let snapshot = buildSnapshot(includeScrollback)
let buildMs = elapsedMs(since: buildStart)

var persistMs: Double?
if persist {
let geometryData = persistedGeometryData(snapshot)
let persistStart = ProcessInfo.processInfo.systemUptime
persistSnapshot(snapshot, geometryData)
persistSnapshot(snapshot)
persistMs = elapsedMs(since: persistStart)
}

Expand Down
185 changes: 81 additions & 104 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -654,13 +654,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
let display: SessionDisplaySnapshot?
}

private nonisolated static let primaryMainWindowFrameAutosaveName: NSWindow.FrameAutosaveName =
"cmux.mainWindow.primary"
private nonisolated static let mainWindowFrameAutosaveNamePrefix = "cmux.mainWindow"
nonisolated static let persistedWindowGeometrySchemaVersion = 2
private nonisolated static let persistedWindowGeometryDefaultsKey = "cmux.session.lastWindowGeometry.v2"
#if DEBUG
nonisolated static var debugPrimaryMainWindowFrameAutosaveName: NSWindow.FrameAutosaveName {
primaryMainWindowFrameAutosaveName
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
nonisolated static var debugPersistedWindowGeometryDefaultsKey: String { persistedWindowGeometryDefaultsKey }
nonisolated static func debugRemoveLegacyPersistedWindowGeometry(
defaults: UserDefaults = .standard
) {
removeLegacyPersistedWindowGeometry(defaults: defaults)
}
#endif
private nonisolated static let legacyPersistedWindowGeometryDefaultsKeys = [
"cmux.session.lastWindowGeometry.v1"
"cmux.session.lastWindowGeometry.v1",
persistedWindowGeometryDefaultsKey,
]

weak var tabManager: TabManager?
Expand Down Expand Up @@ -2513,43 +2525,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
startupSessionSnapshot = SessionPersistenceStore.load()
}

private func persistedWindowGeometry(defaults: UserDefaults = .standard) -> PersistedWindowGeometry? {
Self.removeLegacyPersistedWindowGeometry(defaults: defaults)
guard let data = defaults.data(forKey: Self.persistedWindowGeometryDefaultsKey) else {
return nil
}
guard let payload = Self.decodedPersistedWindowGeometryData(data) else {
defaults.removeObject(forKey: Self.persistedWindowGeometryDefaultsKey)
return nil
}
return payload
}

private func persistWindowGeometry(
frame: SessionRectSnapshot?,
display: SessionDisplaySnapshot?,
defaults: UserDefaults = .standard
) {
Self.removeLegacyPersistedWindowGeometry(defaults: defaults)
guard let data = Self.encodedPersistedWindowGeometryData(frame: frame, display: display) else {
return
}
defaults.set(data, forKey: Self.persistedWindowGeometryDefaultsKey)
}

private nonisolated static func encodedPersistedWindowGeometryData(
frame: SessionRectSnapshot?,
display: SessionDisplaySnapshot?
) -> Data? {
guard let frame else { return nil }
let payload = PersistedWindowGeometry(
version: persistedWindowGeometrySchemaVersion,
frame: frame,
display: display
)
return try? JSONEncoder().encode(payload)
}

nonisolated static func decodedPersistedWindowGeometryData(_ data: Data) -> PersistedWindowGeometry? {
guard let payload = try? JSONDecoder().decode(PersistedWindowGeometry.self, from: data),
payload.version == persistedWindowGeometrySchemaVersion else {
Expand All @@ -2564,14 +2539,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
legacyPersistedWindowGeometryDefaultsKeys.forEach { defaults.removeObject(forKey: $0) }
}

private func persistWindowGeometry(from window: NSWindow?) {
guard let window else { return }
persistWindowGeometry(
frame: SessionRectSnapshot(window.frame),
display: displaySnapshot(for: window)
)
}

private func currentDisplayGeometries() -> (available: [SessionDisplayGeometry], fallback: SessionDisplayGeometry?) {
let available = NSScreen.screens.map { screen in
SessionDisplayGeometry(
Expand All @@ -2590,17 +2557,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return (available, fallback)
}

private func resolvedPersistedWindowGeometryFrame() -> NSRect? {
let displays = currentDisplayGeometries()
let fallbackGeometry = persistedWindowGeometry()
return Self.resolvedWindowFrame(
from: fallbackGeometry?.frame,
display: fallbackGeometry?.display,
availableDisplays: displays.available,
fallbackDisplay: displays.fallback
)
}

private func attemptStartupSessionRestoreIfNeeded(primaryWindow: NSWindow) {
guard !didAttemptStartupSessionRestore else { return }
didAttemptStartupSessionRestore = true
Expand All @@ -2623,18 +2579,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
to: primaryContext,
window: primaryWindow
)
} else {
let displays = currentDisplayGeometries()
let fallbackGeometry = persistedWindowGeometry()
if let restoredFrame = Self.resolvedStartupPrimaryWindowFrame(
primarySnapshot: nil,
fallbackFrame: fallbackGeometry?.frame,
fallbackDisplaySnapshot: fallbackGeometry?.display,
availableDisplays: displays.available,
fallbackDisplay: displays.fallback
) {
primaryWindow.setFrame(restoredFrame, display: true)
}
}

if let startupSnapshot {
Expand Down Expand Up @@ -3321,26 +3265,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
persistSessionSnapshot(
nil,
removeWhenEmpty: removeWhenEmpty,
persistedGeometryData: nil,
synchronously: writeSynchronously
)
return false
}

let persistedGeometryData = snapshot.windows.first.flatMap { primaryWindow in
Self.encodedPersistedWindowGeometryData(
frame: primaryWindow.frame,
display: primaryWindow.display
)
}

#if DEBUG
debugLogSessionSaveSnapshot(snapshot, includeScrollback: includeScrollback)
#endif
persistSessionSnapshot(
snapshot,
removeWhenEmpty: false,
persistedGeometryData: persistedGeometryData,
synchronously: writeSynchronously
)
return true
Expand All @@ -3357,19 +3292,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
buildSnapshot: { [self] includeScrollback in
buildSessionSnapshot(includeScrollback: includeScrollback)
},
persistedGeometryData: { snapshot in
snapshot?.windows.first.flatMap { primaryWindow in
Self.encodedPersistedWindowGeometryData(
frame: primaryWindow.frame,
display: primaryWindow.display
)
}
},
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
persistSnapshot: { [self] snapshot, persistedGeometryData in
persistSnapshot: { [self] snapshot in
persistSessionSnapshot(
snapshot,
removeWhenEmpty: false,
persistedGeometryData: persistedGeometryData,
synchronously: true
)
}
Expand Down Expand Up @@ -3571,19 +3497,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
private func persistSessionSnapshot(
_ snapshot: AppSessionSnapshot?,
removeWhenEmpty: Bool,
persistedGeometryData: Data?,
synchronously: Bool
) {
guard snapshot != nil || removeWhenEmpty || persistedGeometryData != nil else { return }
guard snapshot != nil || removeWhenEmpty else { return }

let writeBlock = {
Self.removeLegacyPersistedWindowGeometry()
if let persistedGeometryData {
UserDefaults.standard.set(
persistedGeometryData,
forKey: Self.persistedWindowGeometryDefaultsKey
)
}
if let snapshot {
_ = SessionPersistenceStore.save(snapshot)
} else if removeWhenEmpty {
Expand Down Expand Up @@ -6843,6 +6762,56 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
)
}

private func mainWindowFrameAutosaveName(windowId: UUID, wantsPrimarySlot: Bool) -> NSWindow.FrameAutosaveName {
if wantsPrimarySlot,
!hasLivePrimaryMainWindowFrameAutosaveOwner() {
return Self.primaryMainWindowFrameAutosaveName
}
return "\(Self.mainWindowFrameAutosaveNamePrefix).\(windowId.uuidString)"
}

private func hasLivePrimaryMainWindowFrameAutosaveOwner(excluding excludedWindow: NSWindow? = nil) -> Bool {
NSApp.windows.contains { window in
if let excludedWindow, window === excludedWindow {
return false
}
return window.frameAutosaveName == Self.primaryMainWindowFrameAutosaveName
}
}

private func promotePrimaryMainWindowFrameAutosaveNameIfNeeded(excluding excludedWindow: NSWindow? = nil) {
guard !hasLivePrimaryMainWindowFrameAutosaveOwner(excluding: excludedWindow) else { return }
guard let survivor = sortedMainWindowContextsForSessionSnapshot()
.compactMap({ resolvedWindow(for: $0) })
.first(where: { window in
guard let excludedWindow else { return true }
return window !== excludedWindow
}) else {
return
}

let previousAutosaveName = survivor.frameAutosaveName
guard previousAutosaveName != Self.primaryMainWindowFrameAutosaveName else { return }
_ = survivor.setFrameAutosaveName(Self.primaryMainWindowFrameAutosaveName)
survivor.saveFrame(usingName: Self.primaryMainWindowFrameAutosaveName)
Comment thread
austinywang marked this conversation as resolved.
Resolved

if !previousAutosaveName.isEmpty,
previousAutosaveName.hasPrefix("\(Self.mainWindowFrameAutosaveNamePrefix).") {
NSWindow.removeFrame(usingName: previousAutosaveName)
}
Comment thread
austinywang marked this conversation as resolved.
Resolved
}

private func removeEphemeralMainWindowFrameAutosaveNameIfNeeded(_ window: NSWindow) {
let autosaveName = window.frameAutosaveName
guard !autosaveName.isEmpty,
autosaveName != Self.primaryMainWindowFrameAutosaveName,
autosaveName.hasPrefix("\(Self.mainWindowFrameAutosaveNamePrefix).") else {
return
}
_ = window.setFrameAutosaveName("")
NSWindow.removeFrame(usingName: autosaveName)
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

@discardableResult
func createMainWindow(
initialWorkspaceTitle: String? = nil,
Expand Down Expand Up @@ -6929,19 +6898,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
let shouldTemporarilyDisallowFullScreenTiling =
sessionWindowSnapshot == nil && sourceWindowIsNativeFullScreen
let restoredFrame = resolvedWindowFrame(from: sessionWindowSnapshot)
let persistedGeometryFrame = (restoredFrame == nil && sourceWindow == nil)
? resolvedPersistedWindowGeometryFrame()
: nil
let initialRect: NSRect
if restoredFrame == nil, let existingFrame {
// Convert frame rect to content rect so the new window matches the
// source window's actual size (frame includes titlebar insets).
initialRect = NSWindow.contentRect(forFrameRect: existingFrame, styleMask: styleMask)
} else if let explicitInitialFrame = restoredFrame ?? persistedGeometryFrame {
} else if let explicitInitialFrame = restoredFrame {
initialRect = NSWindow.contentRect(forFrameRect: explicitInitialFrame, styleMask: styleMask)
} else {
initialRect = CmuxMainWindow.defaultContentRect(styleMask: styleMask)
}
let frameAutosaveName = mainWindowFrameAutosaveName(
windowId: windowId,
wantsPrimarySlot: !hasLivePrimaryMainWindowFrameAutosaveOwner()
)
Comment thread
austinywang marked this conversation as resolved.
Resolved

let window = CmuxMainWindow(
contentRect: initialRect,
Expand Down Expand Up @@ -6969,9 +6939,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
// a movable/resizable window. Empty titlebar drags are routed through
// WindowDragHandleView instead of background dragging.
window.isMovable = true
let explicitInitialFrame = restoredFrame ?? persistedGeometryFrame
let didRegisterFrameAutosaveName = window.setFrameAutosaveName(frameAutosaveName)
let appKitSavedFrameApplied = didRegisterFrameAutosaveName
&& restoredFrame == nil
&& sourceWindow == nil
&& window.setFrameUsingName(frameAutosaveName, force: true)
let explicitInitialFrame = restoredFrame
if let explicitInitialFrame {
window.setFrame(explicitInitialFrame, display: false)
} else if appKitSavedFrameApplied {
lastCascadePoint = NSPoint(x: window.frame.minX, y: window.frame.maxY)
} else if let sourceWindow {
positionNewMainWindow(window, relativeTo: sourceWindow)
} else {
Expand Down Expand Up @@ -7034,7 +7011,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
window.setFrame(explicitInitialFrame, display: true)
#if DEBUG
cmuxDebugLog(
"mainWindow.initialFrameApplied source=\(restoredFrame == nil ? "persistedGeometry" : "sessionSnapshot") window=\(windowId.uuidString.prefix(8)) " +
"mainWindow.initialFrameApplied source=sessionSnapshot window=\(windowId.uuidString.prefix(8)) " +
"applied={\(debugNSRectDescription(window.frame))}"
)
#endif
Expand Down Expand Up @@ -13452,10 +13429,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
let frame = window.frame
lastCascadePoint = NSPoint(x: frame.minX, y: frame.maxY)

// Keep geometry available as a fallback for the next window placement.
persistWindowGeometry(from: window)
removeEphemeralMainWindowFrameAutosaveNameIfNeeded(window)

guard let removed = unregisterMainWindowContext(for: window) else { return }
promotePrimaryMainWindowFrameAutosaveNameIfNeeded(excluding: window)
publishCmuxWindowLifecycle(name: "window.closed", windowId: removed.windowId, origin: "appkit_close")
commandPaletteVisibilityByWindowId.removeValue(forKey: removed.windowId)
commandPalettePendingOpenByWindowId.removeValue(forKey: removed.windowId)
Expand Down
Loading
Loading