-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThemeManager.swift
More file actions
620 lines (507 loc) · 20.9 KB
/
ThemeManager.swift
File metadata and controls
620 lines (507 loc) · 20.9 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
import Foundation
import SwiftUI
// MARK: - Debug Logging
func debugLog(_ message: String) {
let logFile = "/tmp/gtp-debug.log"
let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium)
let logMessage = "[\(timestamp)] \(message)\n"
if let data = logMessage.data(using: .utf8) {
if FileManager.default.fileExists(atPath: logFile) {
if let handle = FileHandle(forWritingAtPath: logFile) {
handle.seekToEndOfFile()
handle.write(data)
handle.closeFile()
}
} else {
FileManager.default.createFile(atPath: logFile, contents: data)
}
}
}
// MARK: - Models
struct ThemeColors {
let background: Color
let foreground: Color
let accent1: Color // Usually red/pink (palette 1 or 5)
let accent2: Color // Usually green/cyan (palette 2 or 6)
static let placeholder = ThemeColors(
background: .gray,
foreground: .white,
accent1: .red,
accent2: .green
)
}
struct Workstream: Codable, Identifiable, Equatable {
var id: UUID = UUID()
var name: String
var theme: String
var directory: String?
var windowTitle: String?
var command: String?
var extraArgs: String? // Additional Ghostty args like --font-size=14
var autoLaunch: Bool = false // Launch this workstream when app starts
static func == (lhs: Workstream, rhs: Workstream) -> Bool {
lhs.id == rhs.id
}
}
// MARK: - ThemeManager
class ThemeManager: ObservableObject {
@Published var themes: [String] = []
@Published var recentThemes: [String] = []
@Published var favoriteThemes: [String] = []
@Published var excludedThemes: [String] = []
@Published var workstreams: [Workstream] = []
@Published var lastSelectedTheme: String?
@Published var defaultRandomDirectory: String = ""
// Cache of launched window PIDs -> workstream names (for window switcher)
@Published var launchedWindows: [pid_t: String] = [:]
// Cache of launched window PIDs -> theme names (for capturing windows as workstreams)
@Published var launchedThemes: [pid_t: String] = [:]
private let maxRecentThemes = 5
private let recentThemesKey = "RecentThemes"
private let favoriteThemesKey = "FavoriteThemes"
private let excludedThemesKey = "ExcludedThemes"
private let workstreamsKey = "Workstreams"
private let defaultRandomDirectoryKey = "DefaultRandomDirectory"
init() {
loadRecentThemes()
loadFavoriteThemes()
loadExcludedThemes()
loadWorkstreams()
loadDefaultRandomDirectory()
fetchThemes()
}
// MARK: - Theme Fetching
func fetchThemes() {
let process = Process()
let pipe = Pipe()
process.executableURL = URL(fileURLWithPath: "/Applications/Ghostty.app/Contents/MacOS/ghostty")
process.arguments = ["+list-themes"]
process.standardOutput = pipe
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
parseThemes(from: output)
}
} catch {
print("Failed to fetch themes: \(error)")
}
}
private func parseThemes(from output: String) {
let lines = output.components(separatedBy: .newlines)
var parsedThemes: [String] = []
for line in lines {
let trimmed = line.trimmingCharacters(in: .whitespaces)
guard !trimmed.isEmpty else { continue }
var themeName = trimmed
if let parenRange = trimmed.range(of: " (", options: .backwards) {
themeName = String(trimmed[..<parenRange.lowerBound])
}
parsedThemes.append(themeName)
}
DispatchQueue.main.async {
self.themes = parsedThemes
}
}
// MARK: - Theme Selection
func pickRandomTheme() -> String? {
guard !themes.isEmpty else { return nil }
// Exclude recent themes and excluded themes
let recentSet = Set(recentThemes)
let excludedSet = Set(excludedThemes)
let availableThemes = themes.filter { !recentSet.contains($0) && !excludedSet.contains($0) }
// If all themes have been used recently or excluded, fall back to non-excluded only
let fallbackThemes = themes.filter { !excludedSet.contains($0) }
let themesToChooseFrom = availableThemes.isEmpty ? fallbackThemes : availableThemes
guard let theme = themesToChooseFrom.randomElement() else { return nil }
addToRecentThemes(theme)
lastSelectedTheme = theme
return theme
}
// MARK: - Launch Ghostty
/// Count windows already using this theme name for auto-naming
private func nextWindowNumber(for theme: String) -> Int {
let existing = launchedWindows.values.filter {
$0 == theme || $0.hasPrefix("\(theme) #")
}
return existing.count + 1
}
func launchGhostty(withTheme theme: String, inDirectory directory: String? = nil, name: String? = nil) {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/Applications/Ghostty.app/Contents/MacOS/ghostty")
var args = ["--theme=\(theme)"]
if let dir = directory, !dir.isEmpty {
args.append("--working-directory=\(dir)")
}
process.arguments = args
do {
try process.run()
let pid = process.processIdentifier
DispatchQueue.main.async {
// Only store a nickname when the caller explicitly provided one
if let providedName = name, !providedName.isEmpty {
self.launchedWindows[pid] = providedName
}
// Always track theme by PID for "Save as Workstream" feature
self.launchedThemes[pid] = theme
}
// Bring Ghostty to the foreground after a brief delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
if let ghosttyApp = NSRunningApplication.runningApplications(withBundleIdentifier: "com.mitchellh.ghostty").first {
ghosttyApp.activate(options: [.activateIgnoringOtherApps])
}
}
addToRecentThemes(theme)
lastSelectedTheme = theme
} catch {
print("Failed to launch Ghostty: \(error)")
}
}
func launchWorkstream(_ workstream: Workstream) {
debugLog("launchWorkstream called for: \(workstream.name)")
var args = ["--theme=\(workstream.theme)"]
if let dir = workstream.directory, !dir.isEmpty {
args.append("--working-directory=\(dir)")
}
// NOTE: We intentionally do NOT set --title here anymore.
// This allows Claude Code to set dynamic window titles with status indicators
// (✳ for waiting, spinner for working). The workstream name is tracked via PID.
// Legacy windowTitle field is preserved for backwards compatibility but not used.
if let cmd = workstream.command, !cmd.isEmpty {
// Wrap command in interactive login shell so PATH is resolved correctly
// Ghostty's -e passes directly to login which doesn't resolve PATH
// -i = interactive (sources .zshrc), -l = login (sources .zprofile)
args.append("-e")
args.append("/bin/zsh")
args.append("-ilc")
args.append(cmd)
}
if let extra = workstream.extraArgs, !extra.isEmpty {
// Parse extra args (space-separated)
let extraParts = extra.components(separatedBy: " ").filter { !$0.isEmpty }
args.append(contentsOf: extraParts)
}
let process = Process()
process.executableURL = URL(fileURLWithPath: "/Applications/Ghostty.app/Contents/MacOS/ghostty")
process.arguments = args
debugLog("Launching ghostty with args: \(args)")
do {
try process.run()
debugLog("Process launched successfully, PID: \(process.processIdentifier)")
// Store PID -> workstream name mapping for window switcher
let pid = process.processIdentifier
DispatchQueue.main.async {
self.launchedWindows[pid] = workstream.name
}
// Bring Ghostty to the foreground after a brief delay
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
if let ghosttyApp = NSRunningApplication.runningApplications(withBundleIdentifier: "com.mitchellh.ghostty").first {
ghosttyApp.activate(options: [.activateIgnoringOtherApps])
}
}
addToRecentThemes(workstream.theme)
lastSelectedTheme = workstream.theme
} catch {
debugLog("Failed to launch Ghostty: \(error)")
}
}
// MARK: - Recent Themes
private func addToRecentThemes(_ theme: String) {
DispatchQueue.main.async {
self.recentThemes.removeAll { $0 == theme }
self.recentThemes.insert(theme, at: 0)
if self.recentThemes.count > self.maxRecentThemes {
self.recentThemes = Array(self.recentThemes.prefix(self.maxRecentThemes))
}
self.saveRecentThemes()
}
}
private func loadRecentThemes() {
if let saved = UserDefaults.standard.stringArray(forKey: recentThemesKey) {
recentThemes = saved
}
}
private func saveRecentThemes() {
UserDefaults.standard.set(recentThemes, forKey: recentThemesKey)
}
// MARK: - Favorite Themes
func isFavorite(_ theme: String) -> Bool {
favoriteThemes.contains(theme)
}
func toggleFavorite(_ theme: String) {
if isFavorite(theme) {
favoriteThemes.removeAll { $0 == theme }
} else {
favoriteThemes.append(theme)
}
saveFavoriteThemes()
}
func addFavorite(_ theme: String) {
guard !isFavorite(theme) else { return }
favoriteThemes.append(theme)
saveFavoriteThemes()
}
func removeFavorite(_ theme: String) {
favoriteThemes.removeAll { $0 == theme }
saveFavoriteThemes()
}
private func loadFavoriteThemes() {
if let saved = UserDefaults.standard.stringArray(forKey: favoriteThemesKey) {
favoriteThemes = saved
}
}
private func saveFavoriteThemes() {
UserDefaults.standard.set(favoriteThemes, forKey: favoriteThemesKey)
}
// MARK: - Excluded Themes
func isExcluded(_ theme: String) -> Bool {
excludedThemes.contains(theme)
}
func toggleExcluded(_ theme: String) {
if isExcluded(theme) {
excludedThemes.removeAll { $0 == theme }
} else {
excludedThemes.append(theme)
}
saveExcludedThemes()
}
func excludeTheme(_ theme: String) {
guard !isExcluded(theme) else { return }
excludedThemes.append(theme)
saveExcludedThemes()
}
func includeTheme(_ theme: String) {
excludedThemes.removeAll { $0 == theme }
saveExcludedThemes()
}
func clearExcludedThemes() {
excludedThemes.removeAll()
saveExcludedThemes()
}
private func loadExcludedThemes() {
if let saved = UserDefaults.standard.stringArray(forKey: excludedThemesKey) {
excludedThemes = saved
}
}
private func saveExcludedThemes() {
UserDefaults.standard.set(excludedThemes, forKey: excludedThemesKey)
}
// MARK: - Workstreams
func addWorkstream(name: String, theme: String, directory: String?, windowTitle: String? = nil, command: String? = nil, autoLaunch: Bool = false, extraArgs: String? = nil) {
let workstream = Workstream(
name: name,
theme: theme,
directory: directory,
windowTitle: windowTitle,
command: command,
extraArgs: extraArgs,
autoLaunch: autoLaunch
)
workstreams.append(workstream)
saveWorkstreams()
}
func updateWorkstream(_ workstream: Workstream) {
if let index = workstreams.firstIndex(where: { $0.id == workstream.id }) {
workstreams[index] = workstream
saveWorkstreams()
}
}
func deleteWorkstream(_ workstream: Workstream) {
workstreams.removeAll { $0.id == workstream.id }
saveWorkstreams()
}
func launchAutoStartWorkstreams() {
let autoLaunchWorkstreams = workstreams.filter { $0.autoLaunch }
for workstream in autoLaunchWorkstreams {
launchWorkstream(workstream)
}
}
/// Find a workstream that matches the given directory path.
/// Used to identify windows not launched by the app (e.g., opened manually).
/// Prefers the most specific (longest path) match when multiple workstreams could match.
func workstreamForDirectory(_ directory: String) -> Workstream? {
var bestMatch: Workstream? = nil
var bestMatchLength = 0
for ws in workstreams {
guard let wsDir = ws.directory, !wsDir.isEmpty else { continue }
// Check exact match or subdirectory match
if directory == wsDir || directory.hasPrefix(wsDir + "/") {
// Prefer longer (more specific) paths
if wsDir.count > bestMatchLength {
bestMatch = ws
bestMatchLength = wsDir.count
}
}
}
return bestMatch
}
/// Get the directory for a workstream by name
func directoryForWorkstream(_ name: String) -> String? {
return workstreams.first { $0.name == name }?.directory
}
/// Get workstream name for a Ghostty PID.
/// First checks launched windows cache, then falls back to directory matching.
func workstreamNameForPID(_ pid: pid_t, shellCwd: String?) -> String? {
print("DEBUG: Looking up PID \(pid), shellCwd: \(shellCwd ?? "nil")")
print("DEBUG: launchedWindows keys: \(launchedWindows.keys.map { $0 })")
// Check if we launched this window
if let name = launchedWindows[pid] {
print("DEBUG: Found in launchedWindows: \(name)")
return name
}
// Fall back to directory matching
if let cwd = shellCwd, let ws = workstreamForDirectory(cwd) {
print("DEBUG: Matched by directory: \(ws.name)")
return ws.name
}
print("DEBUG: No match found")
return nil
}
/// Get theme for a Ghostty PID.
/// Checks workstream launch first, then direct theme launch.
func themeForPID(_ pid: pid_t) -> String? {
// Check if launched via workstream
if let wsName = launchedWindows[pid],
let ws = workstreams.first(where: { $0.name == wsName }) {
return ws.theme
}
// Check if launched via direct theme selection (random, favorites, recent)
return launchedThemes[pid]
}
private func loadWorkstreams() {
if let data = UserDefaults.standard.data(forKey: workstreamsKey),
let decoded = try? JSONDecoder().decode([Workstream].self, from: data) {
workstreams = decoded
}
}
private func saveWorkstreams() {
if let encoded = try? JSONEncoder().encode(workstreams) {
UserDefaults.standard.set(encoded, forKey: workstreamsKey)
}
}
// MARK: - Default Random Directory
private func loadDefaultRandomDirectory() {
if let saved = UserDefaults.standard.string(forKey: defaultRandomDirectoryKey) {
defaultRandomDirectory = saved
}
}
func saveDefaultRandomDirectory() {
UserDefaults.standard.set(defaultRandomDirectory, forKey: defaultRandomDirectoryKey)
}
func exportWorkstreams(_ selected: [Workstream]? = nil) -> Data? {
let toExport = selected ?? workstreams
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
return try? encoder.encode(toExport)
}
func importWorkstreams(from data: Data, replace: Bool = false) -> Int {
guard let imported = try? JSONDecoder().decode([Workstream].self, from: data) else {
return 0
}
if replace {
workstreams = imported
} else {
// Merge - add imported workstreams with new UUIDs to avoid conflicts
for var workstream in imported {
workstream.id = UUID()
workstreams.append(workstream)
}
}
saveWorkstreams()
return imported.count
}
// MARK: - Theme Colors
private var themeColorsCache: [String: ThemeColors] = [:]
private let themesPath = "/Applications/Ghostty.app/Contents/Resources/ghostty/themes"
func getThemeColors(_ themeName: String) -> ThemeColors {
if let cached = themeColorsCache[themeName] {
return cached
}
let colors = parseThemeFile(themeName)
themeColorsCache[themeName] = colors
return colors
}
private func parseThemeFile(_ themeName: String) -> ThemeColors {
let filePath = "\(themesPath)/\(themeName)"
guard let content = try? String(contentsOfFile: filePath, encoding: .utf8) else {
return ThemeColors.placeholder
}
var background: Color = .black
var foreground: Color = .white
var palette1: Color = .red // Red
var palette2: Color = .green // Green
var palette5: Color = .pink // Magenta/Pink
var palette6: Color = .cyan // Cyan
for line in content.components(separatedBy: .newlines) {
let parts = line.split(separator: "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
guard parts.count == 2 else { continue }
let key = parts[0]
let value = parts[1]
if key == "background" {
background = colorFromHex(value)
} else if key == "foreground" {
foreground = colorFromHex(value)
} else if key == "palette" {
// Format: "palette = N=#color" but we split on first =, so value is "N=#color"
let paletteParts = value.split(separator: "=", maxSplits: 1)
if paletteParts.count == 2,
let index = Int(paletteParts[0].trimmingCharacters(in: .whitespaces)) {
let colorHex = String(paletteParts[1]).trimmingCharacters(in: .whitespaces)
let color = colorFromHex(colorHex)
switch index {
case 1: palette1 = color
case 2: palette2 = color
case 5: palette5 = color
case 6: palette6 = color
default: break
}
}
}
}
return ThemeColors(
background: background,
foreground: foreground,
accent1: palette5, // Magenta/Pink - usually vibrant
accent2: palette6 // Cyan - usually vibrant
)
}
func isDarkTheme(_ themeName: String) -> Bool {
let colors = getThemeColors(themeName)
// Convert background color to brightness
// Using the cached colors, extract RGB and calculate luminance
let filePath = "\(themesPath)/\(themeName)"
guard let content = try? String(contentsOfFile: filePath, encoding: .utf8) else {
return true // Default to dark
}
for line in content.components(separatedBy: .newlines) {
let parts = line.split(separator: "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
guard parts.count == 2, parts[0] == "background" else { continue }
var hex = parts[1].trimmingCharacters(in: .whitespaces)
if hex.hasPrefix("#") { hex.removeFirst() }
guard hex.count == 6, let rgb = UInt64(hex, radix: 16) else { return true }
let r = Double((rgb >> 16) & 0xFF) / 255.0
let g = Double((rgb >> 8) & 0xFF) / 255.0
let b = Double(rgb & 0xFF) / 255.0
// Calculate relative luminance
let luminance = 0.299 * r + 0.587 * g + 0.114 * b
return luminance < 0.5
}
return true
}
private func colorFromHex(_ hex: String) -> Color {
var hexString = hex.trimmingCharacters(in: .whitespaces)
if hexString.hasPrefix("#") {
hexString.removeFirst()
}
guard hexString.count == 6,
let rgb = UInt64(hexString, radix: 16) else {
return .gray
}
let r = Double((rgb >> 16) & 0xFF) / 255.0
let g = Double((rgb >> 8) & 0xFF) / 255.0
let b = Double(rgb & 0xFF) / 255.0
return Color(red: r, green: g, blue: b)
}
}