Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ extension ShortcutAction {
first: ShortcutStroke(key: "["),
second: ShortcutStroke(key: "f")
)
case .toggleZenMode:
return StoredShortcut(
first: ShortcutStroke(key: "k", command: true),
second: ShortcutStroke(key: "z")
)
default:
return defaultStroke.map { StoredShortcut(first: $0) }
}
Expand All @@ -41,6 +46,7 @@ extension ShortcutAction {
case .newWindow: return ShortcutStroke(key: "n", command: true, shift: true)
case .closeWindow: return ShortcutStroke(key: "w", command: true, control: true)
case .toggleFullScreen: return ShortcutStroke(key: "f", command: true, control: true)
case .toggleZenMode: return nil
case .quit: return ShortcutStroke(key: "q", command: true)
case .toggleSidebar: return ShortcutStroke(key: "b", command: true)
case .newTab: return ShortcutStroke(key: "n", command: true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public enum ShortcutAction: String, CaseIterable, Sendable, Hashable, SettingCod
case newWindow
case closeWindow
case toggleFullScreen
case toggleZenMode
case quit

// MARK: Workspace
Expand Down Expand Up @@ -177,7 +178,7 @@ extension ShortcutAction {
public var group: Group {
switch self {
case .openSettings, .reloadConfiguration, .showHideAllWindows, .globalSearch,
.newWindow, .closeWindow, .toggleFullScreen, .quit:
.newWindow, .closeWindow, .toggleFullScreen, .toggleZenMode, .quit:
return .app
case .toggleSidebar, .newTab, .newBrowserWorkspace, .saveLayoutTemplate, .openFolder, .reopenPreviousSession, .goToWorkspace,
.commandPalette, .commandPaletteNext, .commandPalettePrevious, .sendFeedback,
Expand Down Expand Up @@ -333,6 +334,8 @@ extension ShortcutAction {
case .newWindow: return "New Window"
case .closeWindow: return "Close Window"
case .toggleFullScreen: return "Toggle Full Screen"
case .toggleZenMode:
return String(localized: "command.toggleZenMode.title", defaultValue: "Toggle Zen Mode")
case .quit: return "Quit cmux"
case .toggleSidebar: return "Toggle Left Sidebar"
case .newTab: return "New Workspace"
Expand Down
17 changes: 17 additions & 0 deletions Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -59635,6 +59635,23 @@
}
}
},
"command.toggleZenMode.title": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Toggle Zen Mode"
}
},
"ja": {
"stringUnit": {
"state": "translated",
"value": "Zenモードを切り替え"
}
}
}
},
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
"command.toggleLeftSidebar.title": {
"localizations": {
"ar": {
Expand Down
132 changes: 108 additions & 24 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
var aboutTitlebarDebugStore: AboutTitlebarDebugStore { debugWindowsCoordinator.aboutTitlebarStore }
/// Coordinates remote tmux (`ssh … tmux -CC`) mirroring; composition-root owned.
let remoteTmuxController = RemoteTmuxController()
/// Coordinates the reversible app-wide Zen Mode session.
private let zenModeController = ZenModeController()
private let systemAppearanceObserver = SystemAppearanceObserver()
private static let reloadConfigurationMenuItemIdentifier = NSUserInterfaceItemIdentifier("com.cmux.reloadConfiguration")
private static let cachedIsRunningUnderXCTest = detectRunningUnderXCTest(ProcessInfo.processInfo.environment)
Expand Down Expand Up @@ -809,9 +811,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
private var splitButtonTooltipRefreshScheduled = false
private var didScheduleGhosttyCrashBreadcrumbCheck = false
private var ghosttyCrashBreadcrumbTask: Task<Void, Never>?
private static let configuredShortcutChordTimeout: TimeInterval = 1
private struct PendingConfiguredShortcutChord {
let firstStroke: ShortcutStroke
let secondStrokes: [ShortcutStroke]
let expiresAt: TimeInterval
let windowNumber: Int?
let fallbackEvent: NSEvent
}
private var pendingConfiguredShortcutChord: PendingConfiguredShortcutChord?
var activeConfiguredShortcutChordPrefixForCurrentEvent: ShortcutStroke?
Expand Down Expand Up @@ -1854,6 +1860,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}

private func prepareForConfirmedAppTermination() {
restoreZenModeForTermination()
isTerminatingApp = true
_ = saveSessionSnapshotIncludingProcessDetectedIndexes(includeScrollback: true, removeWhenEmpty: false)
ClosedItemHistoryStore.shared.flushPendingSaves()
Expand Down Expand Up @@ -1976,6 +1983,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent

func applicationWillTerminate(_ notification: Notification) {
StartupBreadcrumbLog.append("appDelegate.willTerminate.begin")
restoreZenModeForTermination()
// Backstop for any terminate path that did not route through
// prepareForConfirmedAppTermination() (idempotent with the primary arm).
// Apple's promised-pasteboard observer can fire before this delegate
Expand Down Expand Up @@ -2009,6 +2017,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
enableSuddenTerminationIfNeeded()
}

private func restoreZenModeForTermination() {
if let session = zenModeController.restoreForTermination() {
restoreZenModeWindowState(session)
}
}

func applicationWillResignActive(_ notification: Notification) {
guard !isTerminatingApp else { return }
PortScanner.shared.setTrackedAgentScanningPaused(true)
Expand All @@ -2019,6 +2033,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}

func persistSessionForUpdateRelaunch() {
restoreZenModeForTermination()
isTerminatingApp = true
_ = saveSessionSnapshotIncludingProcessDetectedIndexes(includeScrollback: true, removeWhenEmpty: false)
ClosedItemHistoryStore.shared.flushPendingSaves()
Expand Down Expand Up @@ -3458,7 +3473,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
ClosedItemHistoryStore.shared.remapWorkspaceWindowIds(from: originalWindowId, to: context.windowId)
ClosedItemHistoryStore.shared.flushPendingSaves()
}
context.sidebarState.isVisible = snapshot.sidebar.isVisible
context.sidebarState.isVisible = zenModeController.consumeInterruptedSidebarVisibilityRecovery(
windowID: snapshot.windowId ?? context.windowId
) ? true : snapshot.sidebar.isVisible
context.sidebarState.persistedWidth = CGFloat(
SessionPersistencePolicy.sanitizedSidebarWidth(snapshot.sidebar.width)
)
Expand Down Expand Up @@ -5868,6 +5885,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent

private func unregisterMainWindowContext(for window: NSWindow) -> MainWindowContext? {
guard let removed = contextForMainTerminalWindow(window, reindex: false) else { return nil }
_ = zenModeController.endIfTargeting(windowID: removed.windowId)
removed.teardownWindowDock()
let removedKeys = mainWindowContexts.compactMap { key, value in
value === removed ? key : nil
Expand All @@ -5883,6 +5901,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent

// Internal (not private): see notifyMainWindowContextsDidChange.
func discardOrphanedMainWindowContext(_ context: MainWindowContext, allowWindowlessFallback: Bool = false) {
_ = zenModeController.endIfTargeting(windowID: context.windowId)
context.teardownWindowDock()
let contextKeys = mainWindowContexts.compactMap { key, value in
value === context ? key : nil
Expand Down Expand Up @@ -6521,6 +6540,49 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return false
}

/// Toggles app-wide Zen Mode while restoring only state changed on entry.
@discardableResult
func toggleZenMode(preferredWindow: NSWindow? = nil) -> Bool {
if zenModeController.isActive {
guard let session = zenModeController.end() else { return false }
restoreZenModeWindowState(session)
return true
}

guard let context = preferredRegisteredMainWindowContext(preferredWindow: preferredWindow),
let window = resolvedWindow(for: context),
let session = zenModeController.begin(
windowID: context.windowId,
isSidebarVisible: context.sidebarState.isVisible,
isFullScreen: window.styleMask.contains(.fullScreen)
) else {
return false
}

setActiveMainWindow(window)
if session.restoresSidebarVisibility {
context.sidebarState.isVisible = false
}
if session.exitsFullScreen {
window.toggleFullScreen(nil)
}
return true
}

private func restoreZenModeWindowState(_ session: ZenModeController.Session) {
guard let context = mainWindowContexts.values.first(where: { $0.windowId == session.windowID }) else {
return
}
if session.restoresSidebarVisibility, !context.sidebarState.isVisible {
context.sidebarState.isVisible = true
}
if session.exitsFullScreen,
let window = resolvedWindow(for: context),
window.styleMask.contains(.fullScreen) {
window.toggleFullScreen(nil)
}
}

@discardableResult
func toggleRightSidebarInActiveMainWindow(preferredWindow: NSWindow? = nil) -> Bool {
guard let context = preferredRegisteredMainWindowContext(preferredWindow: preferredWindow) else {
Expand Down Expand Up @@ -12805,14 +12867,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
let isControlOnly = hasControl && !hasCommand && !hasOption
let controlDChar = chars == "d" || event.characters == "\u{04}"
let isControlD = isControlOnly && (controlDChar || event.keyCode == 2)
let configuredShortcutEventWindowNumber = configuredShortcutChordWindowNumber(for: event)
if let pendingConfiguredShortcutChord,
pendingConfiguredShortcutChord.windowNumber == configuredShortcutEventWindowNumber {
activeConfiguredShortcutChordPrefixForCurrentEvent = pendingConfiguredShortcutChord.firstStroke
} else {
activeConfiguredShortcutChordPrefixForCurrentEvent = nil
}
pendingConfiguredShortcutChord = nil
activeConfiguredShortcutChordPrefixForCurrentEvent = resolvePendingConfiguredShortcutChord(for: event)
defer { activeConfiguredShortcutChordPrefixForCurrentEvent = nil; clearShortcutEventFocusContextCache(for: event) }
#if DEBUG
if isControlD {
Expand Down Expand Up @@ -13359,6 +13414,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return true
}

if matchConfiguredShortcut(event: event, action: .toggleZenMode) {
return toggleZenMode(preferredWindow: mainWindowForShortcutEvent(event))
}

if handleConfiguredCmuxShortcut(
event: event,
actions: configuredCmuxShortcutActions,
Expand Down Expand Up @@ -15007,14 +15066,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return false
}

let configuredShortcutEventWindowNumber = configuredShortcutChordWindowNumber(for: event)
if let pendingConfiguredShortcutChord,
pendingConfiguredShortcutChord.windowNumber == configuredShortcutEventWindowNumber {
activeConfiguredShortcutChordPrefixForCurrentEvent = pendingConfiguredShortcutChord.firstStroke
} else {
activeConfiguredShortcutChordPrefixForCurrentEvent = nil
}
pendingConfiguredShortcutChord = nil
activeConfiguredShortcutChordPrefixForCurrentEvent = resolvePendingConfiguredShortcutChord(for: event)
defer {
activeConfiguredShortcutChordPrefixForCurrentEvent = nil
clearShortcutEventFocusContextCache(for: event)
Expand Down Expand Up @@ -15173,21 +15225,53 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
shortcuts: [StoredShortcut] = []
) -> Bool {
var seen = Set<StoredShortcut>()
var firstStroke: ShortcutStroke?
var secondStrokes: [ShortcutStroke] = []
let configuredShortcuts = actions.map {
KeyboardShortcutSettings.shortcut(for: $0)
} + shortcuts
for shortcut in configuredShortcuts {
guard seen.insert(shortcut).inserted else { continue }
guard shortcut.hasChord else { continue }
guard let secondStroke = shortcut.secondStroke else { continue }
if matchShortcutStroke(event: event, stroke: shortcut.firstStroke) {
pendingConfiguredShortcutChord = PendingConfiguredShortcutChord(
firstStroke: shortcut.firstStroke,
windowNumber: configuredShortcutChordWindowNumber(for: event)
)
return true
firstStroke = shortcut.firstStroke
if !secondStrokes.contains(secondStroke) {
secondStrokes.append(secondStroke)
}
}
}
return false
guard let firstStroke else { return false }

let pending = PendingConfiguredShortcutChord(
firstStroke: firstStroke,
secondStrokes: secondStrokes,
expiresAt: event.timestamp + Self.configuredShortcutChordTimeout,
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
windowNumber: configuredShortcutChordWindowNumber(for: event),
fallbackEvent: event
)
pendingConfiguredShortcutChord = pending
return true
}

private func resolvePendingConfiguredShortcutChord(for event: NSEvent) -> ShortcutStroke? {
guard let pending = pendingConfiguredShortcutChord else { return nil }
pendingConfiguredShortcutChord = nil

let sameWindow = pending.windowNumber == configuredShortcutChordWindowNumber(for: event)
if event.timestamp <= pending.expiresAt,
sameWindow,
pending.secondStrokes.contains(where: { matchShortcutStroke(event: event, stroke: $0) }) {
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
return pending.firstStroke
}

deliverConfiguredShortcutChordFallback(pending)
return nil
}

private func deliverConfiguredShortcutChordFallback(_ pending: PendingConfiguredShortcutChord) {
let targetWindow = pending.fallbackEvent.window
?? pending.windowNumber.flatMap { NSApp.window(withWindowNumber: $0) }
targetWindow?.sendEvent(pending.fallbackEvent)
}

func configuredCmuxShortcutActions(
Expand Down
13 changes: 13 additions & 0 deletions Sources/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6401,6 +6401,14 @@ struct ContentView: View {
keywords: ["fullscreen", "full", "screen", "window", "toggle"]
)
)
contributions.append(
CommandPaletteCommandContribution(
commandId: "palette.toggleZenMode",
title: constant(String(localized: "command.toggleZenMode.title", defaultValue: "Toggle Zen Mode")),
subtitle: constant(String(localized: "command.toggleSidebar.subtitle", defaultValue: "Layout")),
keywords: ["zen", "focus", "minimal", "fullscreen", "sidebar", "width"]
)
)
contributions.append(
CommandPaletteCommandContribution(
commandId: "palette.reopenClosedBrowserTab",
Expand Down Expand Up @@ -7590,6 +7598,11 @@ struct ContentView: View {
}
window.toggleFullScreen(nil)
}
registry.register(commandId: "palette.toggleZenMode") {
if AppDelegate.shared?.toggleZenMode(preferredWindow: observedWindow ?? NSApp.keyWindow ?? NSApp.mainWindow) != true {
NSSound.beep()
}
}
registry.register(commandId: "palette.reopenClosedBrowserTab") {
if let appDelegate = AppDelegate.shared {
_ = appDelegate.reopenMostRecentlyClosedItem(preferredTabManager: tabManager)
Expand Down
7 changes: 7 additions & 0 deletions Sources/KeyboardShortcutSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ enum KeyboardShortcutSettings {
case newWindow
case closeWindow
case toggleFullScreen
case toggleZenMode
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
case quit

// Titlebar / primary UI
Expand Down Expand Up @@ -204,6 +205,7 @@ enum KeyboardShortcutSettings {
case .newWindow: return String(localized: "shortcut.newWindow.label", defaultValue: "New Window")
case .closeWindow: return String(localized: "shortcut.closeWindow.label", defaultValue: "Close Window")
case .toggleFullScreen: return String(localized: "command.toggleFullScreen.title", defaultValue: "Toggle Full Screen")
case .toggleZenMode: return String(localized: "command.toggleZenMode.title", defaultValue: "Toggle Zen Mode")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
case .quit: return String(localized: "menu.quitCmux", defaultValue: "Quit cmux")
case .toggleSidebar: return String(localized: "shortcut.toggleLeftSidebar.label", defaultValue: "Toggle Left Sidebar")
case .newTab: return String(localized: "shortcut.newWorkspace.label", defaultValue: "New Workspace")
Expand Down Expand Up @@ -347,6 +349,11 @@ enum KeyboardShortcutSettings {
return StoredShortcut(key: "w", command: true, shift: false, option: false, control: true)
case .toggleFullScreen:
return StoredShortcut(key: "f", command: true, shift: false, option: false, control: true)
case .toggleZenMode:
return StoredShortcut(
first: ShortcutStroke(key: "k", command: true, shift: false, option: false, control: false),
second: ShortcutStroke(key: "z", command: false, shift: false, option: false, control: false)
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
)
case .quit:
return StoredShortcut(key: "q", command: true, shift: false, option: false, control: false)
case .toggleSidebar:
Expand Down
Loading
Loading