-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGhosttyThemePickerApp.swift
More file actions
3460 lines (3002 loc) · 127 KB
/
GhosttyThemePickerApp.swift
File metadata and controls
3460 lines (3002 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import SwiftUI
import Carbon
import ApplicationServices
import ServiceManagement
// MARK: - App Delegate for early initialization
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Prompt for screen recording permission if not already granted
if !CGPreflightScreenCaptureAccess() {
CGRequestScreenCaptureAccess()
}
// Start API server immediately on app launch
startBackgroundServices()
}
func applicationWillTerminate(_ notification: Notification) {
WindowTracker.shared.stop()
APIServer.shared.stop()
}
private func startBackgroundServices() {
// Start window tracker
WindowTracker.shared.start()
// Configure API server
APIServer.shared.windowDataProvider = {
WindowTracker.shared.ghosttyWindows
}
APIServer.shared.focusWindowHandler = { axIndex, pid in
WindowTracker.shared.focusWindow(axIndex: axIndex, pid: pid)
}
APIServer.shared.launchRandomHandler = {
guard let themeManager = WindowTracker.shared.themeManager,
let theme = themeManager.pickRandomTheme() else {
return nil
}
let dir = themeManager.defaultRandomDirectory.isEmpty ? nil : themeManager.defaultRandomDirectory
themeManager.launchGhostty(withTheme: theme, inDirectory: dir, name: nil)
return (theme: theme, windowName: theme)
}
APIServer.shared.workstreamsProvider = {
guard let themeManager = WindowTracker.shared.themeManager else {
return []
}
return themeManager.workstreams.map { ws in
WorkstreamResponse(
id: ws.id.uuidString,
name: ws.name,
theme: ws.theme,
directory: ws.directory,
hasCommand: ws.command != nil && !(ws.command?.isEmpty ?? true)
)
}
}
APIServer.shared.launchWorkstreamHandler = { idString in
guard let themeManager = WindowTracker.shared.themeManager,
let uuid = UUID(uuidString: idString),
let workstream = themeManager.workstreams.first(where: { $0.id == uuid }) else {
return nil
}
themeManager.launchWorkstream(workstream)
return (name: workstream.name, theme: workstream.theme)
}
APIServer.shared.openQuickLaunchHandler = {
DispatchQueue.main.async {
QuickLaunchPanel.shared.show(themeManager: WindowTracker.shared.themeManager)
}
}
// Start API server
APIServer.shared.start()
print("Background services started")
}
}
@main
struct GhosttyThemePickerApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject private var themeManager = ThemeManager()
@State private var showingWorkstreams = false
@State private var hasLaunchedAutoStart = false
@StateObject private var hotkeyManager = HotkeyManager()
var body: some Scene {
MenuBarExtra {
MenuContent(themeManager: themeManager, showingWorkstreams: $showingWorkstreams)
.onAppear {
debugLog("MenuContent onAppear called")
hotkeyManager.themeManager = themeManager
hotkeyManager.registerHotkey()
// Connect WindowTracker to themeManager for workstream lookups
WindowTracker.shared.themeManager = themeManager
// Launch auto-start workstreams on first appearance
if !hasLaunchedAutoStart {
hasLaunchedAutoStart = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
themeManager.launchAutoStartWorkstreams()
}
}
}
} label: {
Label("Ghostty Theme Picker", systemImage: "terminal")
}
Window("Settings", id: "workstreams") {
SettingsView(themeManager: themeManager, hotkeyManager: hotkeyManager)
}
.windowResizability(.contentSize)
Window("Quick Launch", id: "quicklaunch") {
QuickLaunchView(viewModel: QuickLaunchViewModel(themeManager: themeManager))
}
.windowStyle(.hiddenTitleBar)
.windowResizability(.contentSize)
.defaultPosition(.center)
}
}
// MARK: - Hotkey Config
struct HotkeyConfig: Codable, Equatable {
var keyCode: UInt32
var modifiers: UInt32 // Carbon modifier flags
var enabled: Bool
static let defaultQuickLaunch = HotkeyConfig(keyCode: 5, modifiers: UInt32(controlKey | optionKey), enabled: true)
static let defaultWindowSwitcher = HotkeyConfig(keyCode: 35, modifiers: UInt32(controlKey | optionKey), enabled: true)
var displayString: String {
var parts: [String] = []
if modifiers & UInt32(controlKey) != 0 { parts.append("⌃") }
if modifiers & UInt32(optionKey) != 0 { parts.append("⌥") }
if modifiers & UInt32(shiftKey) != 0 { parts.append("⇧") }
if modifiers & UInt32(cmdKey) != 0 { parts.append("⌘") }
parts.append(keyCodeToString(keyCode))
return parts.joined()
}
}
func keyCodeToString(_ keyCode: UInt32) -> String {
let map: [UInt32: String] = [
0: "A", 1: "S", 2: "D", 3: "F", 4: "H", 5: "G", 6: "Z", 7: "X",
8: "C", 9: "V", 11: "B", 12: "Q", 13: "W", 14: "E", 15: "R",
16: "Y", 17: "T", 18: "1", 19: "2", 20: "3", 21: "4", 22: "6",
23: "5", 24: "=", 25: "9", 26: "7", 27: "-", 28: "8", 29: "0",
30: "]", 31: "O", 32: "U", 33: "[", 34: "I", 35: "P", 36: "↩",
37: "L", 38: "J", 39: "'", 40: "K", 41: ";", 42: "\\", 43: ",",
44: "/", 45: "N", 46: ".", 47: "M", 48: "⇥", 49: "Space",
50: "`", 51: "⌫", 53: "⎋",
// F-keys
96: "F5", 97: "F6", 98: "F7", 99: "F3", 100: "F8",
101: "F9", 109: "F10", 103: "F11", 111: "F12",
105: "F13", 107: "F14", 113: "F15",
118: "F4", 120: "F2", 122: "F1",
// Arrow keys
123: "←", 124: "→", 125: "↓", 126: "↑",
]
return map[keyCode] ?? "Key\(keyCode)"
}
func carbonModifiers(from flags: NSEvent.ModifierFlags) -> UInt32 {
var mods: UInt32 = 0
if flags.contains(.control) { mods |= UInt32(controlKey) }
if flags.contains(.option) { mods |= UInt32(optionKey) }
if flags.contains(.shift) { mods |= UInt32(shiftKey) }
if flags.contains(.command) { mods |= UInt32(cmdKey) }
return mods
}
// MARK: - Hotkey Manager (Carbon-based)
class HotkeyManager: ObservableObject {
var themeManager: ThemeManager?
private var hotkeyRefG: EventHotKeyRef?
private var hotkeyRefP: EventHotKeyRef?
private var eventHandlerInstalled = false
static var instance: HotkeyManager?
@Published var quickLaunchConfig: HotkeyConfig = .defaultQuickLaunch
@Published var windowSwitcherConfig: HotkeyConfig = .defaultWindowSwitcher
private static let quickLaunchKey = "HotkeyQuickLaunch"
private static let windowSwitcherKey = "HotkeyWindowSwitcher"
func loadFromDefaults() {
if let data = UserDefaults.standard.data(forKey: Self.quickLaunchKey),
let config = try? JSONDecoder().decode(HotkeyConfig.self, from: data) {
quickLaunchConfig = config
}
if let data = UserDefaults.standard.data(forKey: Self.windowSwitcherKey),
let config = try? JSONDecoder().decode(HotkeyConfig.self, from: data) {
windowSwitcherConfig = config
}
}
func saveToDefaults() {
if let data = try? JSONEncoder().encode(quickLaunchConfig) {
UserDefaults.standard.set(data, forKey: Self.quickLaunchKey)
}
if let data = try? JSONEncoder().encode(windowSwitcherConfig) {
UserDefaults.standard.set(data, forKey: Self.windowSwitcherKey)
}
}
func registerHotkey() {
HotkeyManager.instance = self
loadFromDefaults()
if !eventHandlerInstalled {
var eventType = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
InstallEventHandler(GetApplicationEventTarget(), { (_, event, _) -> OSStatus in
var hotKeyID = EventHotKeyID()
GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, MemoryLayout<EventHotKeyID>.size, nil, &hotKeyID)
if hotKeyID.id == 1 {
HotkeyManager.instance?.handleHotkeyG()
} else if hotKeyID.id == 2 {
HotkeyManager.instance?.handleHotkeyP()
}
return noErr
}, 1, &eventType, nil, nil)
eventHandlerInstalled = true
}
registerConfiguredHotkeys()
}
func reregisterHotkeys() {
unregisterAll()
registerConfiguredHotkeys()
saveToDefaults()
}
private func registerConfiguredHotkeys() {
if quickLaunchConfig.enabled {
var hotKeyIDG = EventHotKeyID()
hotKeyIDG.signature = OSType(0x4754504B) // "GTPK"
hotKeyIDG.id = 1
let status = RegisterEventHotKey(quickLaunchConfig.keyCode, quickLaunchConfig.modifiers, hotKeyIDG, GetApplicationEventTarget(), 0, &hotkeyRefG)
if status == noErr {
print("Global hotkey registered: \(quickLaunchConfig.displayString) (Quick Launch)")
}
}
if windowSwitcherConfig.enabled {
var hotKeyIDP = EventHotKeyID()
hotKeyIDP.signature = OSType(0x4754504B) // "GTPK"
hotKeyIDP.id = 2
let status = RegisterEventHotKey(windowSwitcherConfig.keyCode, windowSwitcherConfig.modifiers, hotKeyIDP, GetApplicationEventTarget(), 0, &hotkeyRefP)
if status == noErr {
print("Global hotkey registered: \(windowSwitcherConfig.displayString) (Window Switcher)")
}
}
}
private func unregisterAll() {
if let ref = hotkeyRefG {
UnregisterEventHotKey(ref)
hotkeyRefG = nil
}
if let ref = hotkeyRefP {
UnregisterEventHotKey(ref)
hotkeyRefP = nil
}
}
private func handleHotkeyG() {
DispatchQueue.main.async {
QuickLaunchPanel.shared.show(themeManager: self.themeManager)
}
}
private func handleHotkeyP() {
DispatchQueue.main.async {
WindowSwitcherPanel.shared.show()
}
}
deinit {
unregisterAll()
}
}
// MARK: - Window Switcher Panel
class KeyHandlingPanel: NSPanel {
var keyHandler: ((NSEvent) -> Bool)?
override func sendEvent(_ event: NSEvent) {
if event.type == .keyDown, let handler = keyHandler, handler(event) {
// Event was handled, don't pass it on
return
}
super.sendEvent(event)
}
}
class WindowSwitcherPanel {
static let shared = WindowSwitcherPanel()
private var panel: KeyHandlingPanel?
func show() {
if let existing = panel {
existing.close()
}
let panel = KeyHandlingPanel(
contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
styleMask: [.titled, .closable, .fullSizeContentView, .nonactivatingPanel],
backing: .buffered,
defer: false
)
panel.titleVisibility = .hidden
panel.titlebarAppearsTransparent = true
panel.isMovableByWindowBackground = true
panel.level = .floating
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
panel.isReleasedWhenClosed = false
panel.backgroundColor = NSColor.windowBackgroundColor
let view = WindowSwitcherView(themeManager: HotkeyManager.instance?.themeManager, panel: panel) {
panel.close()
}
panel.contentView = NSHostingView(rootView: view)
panel.center()
panel.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
self.panel = panel
}
func close() {
panel?.close()
panel = nil
}
}
// MARK: - Window Switcher View
/// Represents Claude's state in a terminal window
enum ClaudeState: Int, Comparable {
case notRunning = 0 // No Claude in this window
case working = 1 // Claude is processing (spinner in title)
case running = 2 // Claude detected via process tree (can't determine exact state)
case waiting = 3 // Claude waiting for input (✳ in title) - at prompt
case asking = 4 // Claude asked a question and waiting for answer (highest priority)
static func < (lhs: ClaudeState, rhs: ClaudeState) -> Bool {
lhs.rawValue < rhs.rawValue
}
var icon: String {
switch self {
case .asking: return "questionmark.circle"
case .waiting: return "hourglass"
case .running: return "terminal"
case .working: return "gearshape"
case .notRunning: return "terminal"
}
}
var label: String {
switch self {
case .asking: return "Question"
case .waiting: return "Ready"
case .running: return "Claude"
case .working: return "Working"
case .notRunning: return ""
}
}
}
/// Data captured from a Ghostty window for creating a workstream
struct CapturedWindow {
let directory: String
let title: String
let theme: String? // nil only if window was opened outside our app
let pid: pid_t
/// Suggested workstream name derived from directory
var suggestedName: String {
let url = URL(fileURLWithPath: directory)
let lastComponent = url.lastPathComponent
if lastComponent.isEmpty || lastComponent == "/" {
return "Home"
}
return lastComponent
}
}
/// Helper to capture the frontmost Ghostty window
class WindowCapture {
/// Capture the frontmost Ghostty window's info
static func captureFrontmostGhosttyWindow(themeManager: ThemeManager) -> CapturedWindow? {
// Get frontmost Ghostty window using CGWindowList
let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
guard let windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {
return nil
}
// Find frontmost Ghostty window (lowest layer number = frontmost)
var ghosttyWindows: [(info: [String: Any], layer: Int)] = []
for window in windowList {
guard let ownerName = window["kCGWindowOwnerName"] as? String,
ownerName.lowercased() == "ghostty",
let layer = window["kCGWindowLayer"] as? Int else {
continue
}
ghosttyWindows.append((info: window, layer: layer))
}
// Sort by layer (lower = more front)
ghosttyWindows.sort { $0.layer < $1.layer }
guard let frontmost = ghosttyWindows.first else {
return nil
}
let windowInfo = frontmost.info
guard let ownerPID = windowInfo["kCGWindowOwnerPID"] as? Int else {
return nil
}
let pid = pid_t(ownerPID)
let title = windowInfo["kCGWindowName"] as? String ?? "Ghostty"
// Get shell cwd
guard let directory = getShellCwd(ghosttyPid: pid) else {
return nil
}
// Look up theme from our caches
let theme = themeManager.themeForPID(pid)
return CapturedWindow(
directory: directory,
title: title,
theme: theme,
pid: pid
)
}
/// Get the current working directory of the shell inside a Ghostty window
private static func getShellCwd(ghosttyPid: pid_t) -> String? {
// First, get process tree to find the shell
let psTask = Process()
psTask.executableURL = URL(fileURLWithPath: "/bin/ps")
psTask.arguments = ["-eo", "pid,ppid,comm"]
let psPipe = Pipe()
psTask.standardOutput = psPipe
psTask.standardError = FileHandle.nullDevice
do {
try psTask.run()
} catch {
return nil
}
let psData = psPipe.fileHandleForReading.readDataToEndOfFile()
psTask.waitUntilExit()
guard let psOutput = String(data: psData, encoding: .utf8) else { return nil }
// Parse process tree
var processTree: [pid_t: (ppid: pid_t, comm: String)] = [:]
for line in psOutput.components(separatedBy: "\n") {
let parts = line.trimmingCharacters(in: .whitespaces).split(separator: " ", maxSplits: 2)
guard parts.count >= 3,
let pid = pid_t(parts[0]),
let ppid = pid_t(parts[1]) else { continue }
let comm = String(parts[2])
processTree[pid] = (ppid: ppid, comm: comm)
}
// Find login -> shell chain
guard let loginPid = processTree.first(where: {
$0.value.ppid == ghosttyPid && $0.value.comm.contains("login")
})?.key else {
return nil
}
guard let shellEntry = processTree.first(where: {
$0.value.ppid == loginPid
}) else {
return nil
}
let shellPid = shellEntry.key
// Get cwd using lsof
let lsofTask = Process()
lsofTask.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
lsofTask.arguments = ["-a", "-p", "\(shellPid)", "-d", "cwd", "-F", "n"]
let lsofPipe = Pipe()
lsofTask.standardOutput = lsofPipe
lsofTask.standardError = FileHandle.nullDevice
do {
try lsofTask.run()
} catch {
return nil
}
let lsofData = lsofPipe.fileHandleForReading.readDataToEndOfFile()
lsofTask.waitUntilExit()
guard let lsofOutput = String(data: lsofData, encoding: .utf8) else { return nil }
for line in lsofOutput.components(separatedBy: "\n") {
if line.hasPrefix("n") {
return String(line.dropFirst())
}
}
return nil
}
}
struct GhosttyWindow: Identifiable {
let id: Int
let name: String // Window title (e.g., "✳ Claude Code" or "~/Projects")
let axIndex: Int // Index for AppleScript (1-based, per-process)
let pid: pid_t // Process ID this window belongs to
var workstreamName: String? // Matched workstream name (via PID cache or directory)
var shellCwd: String? // Current working directory of shell
var hasClaudeProcess: Bool = false // Whether a Claude process is running in this window
var hookState: String? // State from Claude Code hook ("asking" or "waiting")
/// Determine Claude's state based on window title, hook state, and process detection
var claudeState: ClaudeState {
// Check title for exact state indicators
if let firstChar = name.first {
// ✳ (U+2733) = waiting for input - refine with hook state if available
if firstChar == "✳" {
// Use hook state to distinguish "asking" vs "waiting"
if hookState == "asking" {
return .asking
}
return .waiting
}
// Braille spinner characters = working
let spinnerChars: Set<Character> = ["⠁", "⠂", "⠄", "⠈", "⠐", "⠠", "⡀", "⢀"]
if spinnerChars.contains(firstChar) {
return .working
}
}
// Fall back to process detection
return hasClaudeProcess ? .running : .notRunning
}
/// Display name: prefer workstream name, fall back to shortened path or title
var displayName: String {
if let ws = workstreamName {
return ws
}
// If title looks like a path, shorten it
if name.hasPrefix("/") || name.hasPrefix("~") {
return (name as NSString).lastPathComponent
}
return name
}
}
class WindowSwitcherViewModel: ObservableObject {
@Published var windows: [GhosttyWindow] = []
@Published var searchText: String = ""
@Published var selectedIndex: Int = 0
@Published var hasScreenRecordingPermission: Bool = false
weak var themeManager: ThemeManager?
/// Windows filtered by search and sorted by Claude state (waiting first)
var filteredWindows: [GhosttyWindow] {
var result = windows
if !searchText.isEmpty {
result = result.filter { window in
window.name.localizedCaseInsensitiveContains(searchText) ||
(window.workstreamName?.localizedCaseInsensitiveContains(searchText) ?? false)
}
}
// Sort by Claude state (waiting > running > working > notRunning)
return result.sorted { $0.claudeState > $1.claudeState }
}
/// Group windows by Claude state for sectioned display
var groupedWindows: [(state: ClaudeState, windows: [GhosttyWindow])] {
let sorted = filteredWindows
var groups: [(ClaudeState, [GhosttyWindow])] = []
let asking = sorted.filter { $0.claudeState == .asking }
let waiting = sorted.filter { $0.claudeState == .waiting }
let running = sorted.filter { $0.claudeState == .running }
let working = sorted.filter { $0.claudeState == .working }
let other = sorted.filter { $0.claudeState == .notRunning }
if !asking.isEmpty { groups.append((.asking, asking)) }
if !waiting.isEmpty { groups.append((.waiting, waiting)) }
if !running.isEmpty { groups.append((.running, running)) }
if !working.isEmpty { groups.append((.working, working)) }
if !other.isEmpty { groups.append((.notRunning, other)) }
return groups
}
// MARK: - Cached Process Data (for efficient lookups)
var cachedProcessTree: [pid_t: (ppid: pid_t, comm: String)] = [:] // Internal for debug
private var cachedClaudePids: Set<pid_t> = []
private var cachedShellCwds: [pid_t: String] = [:]
var debugLog: ((String) -> Void)? // Debug logging callback
// MARK: - Workstream Name Cache (persists across Window Switcher opens)
// Maps PID to workstream name. Value of nil means "checked, no match".
// This cache is NOT cleared on each open - it persists to make repeat opens instant.
private var workstreamCache: [pid_t: String?] = [:]
/// Apply cached workstream names to windows (for immediate display)
func applyCachedWorkstreamNames(to windows: inout [GhosttyWindow]) {
for i in windows.indices {
let pid = windows[i].pid
// Check app-launched windows first (always authoritative)
if let name = themeManager?.launchedWindows[pid] {
windows[i].workstreamName = name
}
// Then check our runtime cache
else if let cached = workstreamCache[pid], let name = cached {
windows[i].workstreamName = name
}
}
}
/// Check if a window needs workstream enrichment
func needsWorkstreamEnrichment(pid: pid_t) -> Bool {
// Already in app-launched cache
if themeManager?.launchedWindows[pid] != nil {
return false
}
// Already in our workstream cache (even if nil = no match)
if workstreamCache.keys.contains(pid) {
return false
}
return true
}
/// Cache a workstream lookup result
func cacheWorkstreamName(_ name: String?, forPid pid: pid_t) {
workstreamCache[pid] = name
}
/// Clean up cache entries for PIDs that no longer exist
func cleanupWorkstreamCache(activePids: Set<pid_t>) {
workstreamCache = workstreamCache.filter { activePids.contains($0.key) }
}
/// Load all process data in one shot for efficient lookups
func loadProcessCache() {
cachedProcessTree.removeAll()
cachedClaudePids.removeAll()
cachedShellCwds.removeAll()
// Single ps call to get all process info
let task = Process()
task.executableURL = URL(fileURLWithPath: "/bin/ps")
task.arguments = ["-eo", "pid,ppid,comm"]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = FileHandle.nullDevice
do {
try task.run()
} catch {
return
}
// Read data before waiting (to avoid deadlock with large output)
let data = pipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()
guard let output = String(data: data, encoding: .utf8) else { return }
for line in output.components(separatedBy: "\n") {
let parts = line.trimmingCharacters(in: .whitespaces).split(separator: " ", maxSplits: 2)
guard parts.count >= 3,
let pid = pid_t(parts[0]),
let ppid = pid_t(parts[1]) else { continue }
let comm = String(parts[2])
cachedProcessTree[pid] = (ppid: ppid, comm: comm)
if comm.lowercased() == "claude" {
cachedClaudePids.insert(pid)
}
}
}
// MARK: - Hook State Reading
private var hookStateCache: [String: (state: String, timestamp: TimeInterval)] = [:]
func loadHookStates() {
let stateDir = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".claude-states")
guard let files = try? FileManager.default.contentsOfDirectory(
at: stateDir,
includingPropertiesForKeys: nil
) else {
return
}
for file in files where file.pathExtension == "json" {
guard let data = try? Data(contentsOf: file),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let state = json["state"] as? String,
let cwd = json["cwd"] as? String,
let timestamp = json["timestamp"] as? TimeInterval else {
continue
}
if let existing = hookStateCache[cwd] {
if timestamp > existing.timestamp {
hookStateCache[cwd] = (state: state, timestamp: timestamp)
}
} else {
hookStateCache[cwd] = (state: state, timestamp: timestamp)
}
}
}
func getHookState(forCwd cwd: String) -> String? {
if let cached = hookStateCache[cwd] {
return cached.state
}
for (cachedCwd, cached) in hookStateCache {
if cwd.hasPrefix(cachedCwd + "/") || cachedCwd.hasPrefix(cwd + "/") {
return cached.state
}
}
return nil
}
// MARK: - Shell CWD Detection
/// Get the current working directory of the shell running inside a Ghostty window
func getShellCwd(ghosttyPid: pid_t) -> String? {
// Find login -> shell chain using cached data
guard let loginPid = cachedProcessTree.first(where: {
$0.value.ppid == ghosttyPid && $0.value.comm.contains("login")
})?.key else {
debugLog?("getShellCwd(\(ghosttyPid)): no login found")
return nil
}
guard let shellEntry = cachedProcessTree.first(where: {
$0.value.ppid == loginPid
}) else {
debugLog?("getShellCwd(\(ghosttyPid)): no shell found under login \(loginPid)")
return nil
}
let shellPid = shellEntry.key
debugLog?("getShellCwd(\(ghosttyPid)): found shell \(shellPid) (\(shellEntry.value.comm))")
// Check cache first
if let cached = cachedShellCwds[shellPid] {
return cached
}
// Get cwd using lsof (only for shells we need)
let cwd = getCwd(of: shellPid)
debugLog?("getShellCwd(\(ghosttyPid)): lsof returned \(cwd ?? "nil")")
if let cwd = cwd {
cachedShellCwds[shellPid] = cwd
}
return cwd
}
private func getCwd(of pid: pid_t) -> String? {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof")
task.arguments = ["-a", "-p", "\(pid)", "-d", "cwd", "-F", "n"]
let pipe = Pipe()
let errPipe = Pipe()
task.standardOutput = pipe
task.standardError = errPipe
do {
try task.run()
} catch {
debugLog?("getCwd(\(pid)): failed to run lsof: \(error)")
return nil
}
// Read data BEFORE waiting to avoid deadlock
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let errData = errPipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()
let exitCode = task.terminationStatus
let output = String(data: data, encoding: .utf8) ?? ""
let errOutput = String(data: errData, encoding: .utf8) ?? ""
debugLog?("getCwd(\(pid)): exit=\(exitCode), stdout='\(output.prefix(100))', stderr='\(errOutput.prefix(100))'")
for line in output.components(separatedBy: "\n") {
if line.hasPrefix("n") {
return String(line.dropFirst())
}
}
return nil
}
// MARK: - Claude Process Detection
/// Check if a Claude process is running under the given Ghostty PID
func hasClaudeProcess(ghosttyPid: pid_t) -> Bool {
for claudePid in cachedClaudePids {
if traceToGhostty(from: claudePid) == ghosttyPid {
return true
}
}
return false
}
private func traceToGhostty(from pid: pid_t) -> pid_t? {
var current = pid
for _ in 0..<15 {
guard let info = cachedProcessTree[current] else { return nil }
let parent = info.ppid
if parent <= 1 { return nil }
// Check if parent is a Ghostty window we know about
if windows.contains(where: { $0.pid == parent }) {
return parent
}
current = parent
}
return nil
}
func handleKeyDown(_ event: NSEvent, onDismiss: (() -> Void)?) -> Bool {
guard !filteredWindows.isEmpty else { return false }
switch Int(event.keyCode) {
case 125: // Down arrow
selectedIndex = (selectedIndex + 1) % filteredWindows.count
return true
case 126: // Up arrow
selectedIndex = (selectedIndex - 1 + filteredWindows.count) % filteredWindows.count
return true
case 36, 76: // Enter/Return
let window = filteredWindows[selectedIndex]
focusWindow(axIndex: window.axIndex, pid: window.pid)
onDismiss?()
return true
default:
return false
}
}
func focusWindow(axIndex: Int, pid: pid_t) {
// Use NSRunningApplication to activate the specific process by PID
guard let app = NSRunningApplication(processIdentifier: pid) else {
print("Could not find application with PID \(pid)")
return
}
// Activate the specific process
app.activate(options: [.activateIgnoringOtherApps])
// Use Accessibility API to raise the specific window
let appElement = AXUIElementCreateApplication(pid)
var windowsRef: CFTypeRef?
let result = AXUIElementCopyAttributeValue(appElement, kAXWindowsAttribute as CFString, &windowsRef)
guard result == .success,
let windows = windowsRef as? [AXUIElement],
axIndex > 0 && axIndex <= windows.count else {
print("Could not get window \(axIndex) for PID \(pid)")
return
}
let windowElement = windows[axIndex - 1] // axIndex is 1-based
AXUIElementPerformAction(windowElement, kAXRaiseAction as CFString)
}
}
struct WindowSwitcherView: View {
@StateObject private var viewModel = WindowSwitcherViewModel()
var themeManager: ThemeManager?
weak var panel: KeyHandlingPanel?
var onDismiss: (() -> Void)?
init(themeManager: ThemeManager? = nil, panel: KeyHandlingPanel? = nil, onDismiss: (() -> Void)? = nil) {
self.themeManager = themeManager
self.panel = panel
self.onDismiss = onDismiss
}
// Check if Screen Recording permission is granted
private func checkPermissions() {
viewModel.hasScreenRecordingPermission = CGPreflightScreenCaptureAccess()
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
// Header
HStack {
Image(systemName: "macwindow.on.rectangle")
.foregroundColor(.accentColor)
Text("Switch Window")
.font(.headline)
Spacer()
Text("⌃⌥P")
.font(.caption)
.foregroundColor(.secondary)
}
.padding()
.background(Color(NSColor.controlBackgroundColor))
Divider()
// Search field
TextField("Search windows...", text: $viewModel.searchText)
.textFieldStyle(.roundedBorder)
.padding(.horizontal)
.padding(.top, 8)
// Window list
if !viewModel.hasScreenRecordingPermission {
VStack(spacing: 16) {
Spacer()
Image(systemName: "eye.trianglebadge.exclamationmark")
.font(.system(size: 40))
.foregroundColor(.orange)
Text("Screen Recording Permission Required")
.font(.headline)
Text("Window names require Screen Recording permission to be displayed.")
.font(.caption)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal)
VStack(spacing: 8) {
Button {
// Open System Settings to Privacy & Security > Screen Recording
if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") {
NSWorkspace.shared.open(url)
}
} label: {
HStack {
Image(systemName: "gear")
Text("Open System Settings")
}
}
Button {
checkPermissions()
if viewModel.hasScreenRecordingPermission {
loadWindows()
}
} label: {
HStack {
Image(systemName: "arrow.clockwise")
Text("Retry")
}
}
}
Spacer()
}
.frame(maxWidth: .infinity)
} else if viewModel.filteredWindows.isEmpty {
VStack {
Spacer()
Text(viewModel.windows.isEmpty ? "No Ghostty windows open" : "No matching windows")
.foregroundColor(.secondary)
Spacer()
}
.frame(maxWidth: .infinity)
} else {
ScrollViewReader { proxy in
ScrollView {
VStack(spacing: 4) {
ForEach(Array(viewModel.filteredWindows.enumerated()), id: \.element.id) { index, window in
// Section header when state changes
if index == 0 || viewModel.filteredWindows[index - 1].claudeState != window.claudeState {
sectionHeader(for: window.claudeState)