-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathXcodeThemeController.swift
More file actions
286 lines (256 loc) · 11 KB
/
XcodeThemeController.swift
File metadata and controls
286 lines (256 loc) · 11 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
import AppKit
import Foundation
import Highlightr
import Logger
import XcodeInspector
public class XcodeThemeController {
var syncTriggerTask: Task<Void, Error>? // to be removed
public init() {
}
public func start() {
let defaultHighlightrThemeManager = Highlightr.themeManager
Highlightr.themeManager = HighlightrThemeManager(
defaultManager: defaultHighlightrThemeManager,
controller: self
)
syncXcodeThemeIfNeeded(forceRefresh: true)
guard syncTriggerTask == nil else {
Logger.service.error("XcodeThemeController.start() invoked multiple times.")
return
}
syncTriggerTask = Task { [weak self] in
let notifications = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.didActivateApplicationNotification)
for await notification in notifications {
try Task.checkCancellation()
guard let app = notification
.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
else { continue }
guard app.isCopilotForXcodeExtensionService || app.isXcode else { continue }
guard let self else { return }
self.syncXcodeThemeIfNeeded()
}
}
Timer.scheduledTimer(
withTimeInterval: 60,
repeats: true
) { [weak self] _ in
guard XcodeInspector.shared.activeApplication?.isXcode == true else { return }
self?.syncXcodeThemeIfNeeded()
}
}
}
extension XcodeThemeController {
func syncXcodeThemeIfNeeded(forceRefresh: Bool = false) {
guard UserDefaults.shared.value(for: \.syncSuggestionHighlightTheme)
|| UserDefaults.shared.value(for: \.syncPromptToCodeHighlightTheme)
|| UserDefaults.shared.value(for: \.syncChatCodeHighlightTheme)
else { return }
guard let directories = createSupportDirectoriesIfNeeded() else { return }
defer {
UserDefaults.shared.set(
Date().timeIntervalSince1970,
for: \.lastSyncedHighlightJSThemeCreatedAt
)
}
let xcodeUserDefaults = UserDefaults(suiteName: "com.apple.dt.Xcode")!
if let darkThemeName = xcodeUserDefaults
.value(forKey: "XCFontAndColorCurrentDarkTheme") as? String
{
syncXcodeThemeIfNeeded(
xcodeThemeName: darkThemeName,
light: false,
in: directories.themeDirectory,
forceRefresh: forceRefresh
)
}
if let lightThemeName = xcodeUserDefaults
.value(forKey: "XCFontAndColorCurrentTheme") as? String
{
syncXcodeThemeIfNeeded(
xcodeThemeName: lightThemeName,
light: true,
in: directories.themeDirectory,
forceRefresh: forceRefresh
)
}
}
func syncXcodeThemeIfNeeded(
xcodeThemeName: String,
light: Bool,
in directoryURL: URL,
forceRefresh: Bool = false
) {
let targetName = light ? "highlightjs-light" : "highlightjs-dark"
guard let xcodeThemeURL = locateXcodeTheme(named: xcodeThemeName) else {
Logger.service.error("Xcode theme not found: \(xcodeThemeName)")
return
}
let targetThemeURL = directoryURL.appendingPathComponent(targetName)
let lastSyncTimestamp = UserDefaults.shared
.value(for: \.lastSyncedHighlightJSThemeCreatedAt)
let shouldSync = {
if forceRefresh { return true }
if light, UserDefaults.shared.value(for: \.lightXcodeTheme) == nil { return true }
if !light, UserDefaults.shared.value(for: \.darkXcodeTheme) == nil { return true }
if light, xcodeThemeName != UserDefaults.shared.value(for: \.lightXcodeThemeName) {
return true
}
if !light, xcodeThemeName != UserDefaults.shared.value(for: \.darkXcodeThemeName) {
return true
}
if !FileManager.default.fileExists(atPath: targetThemeURL.path) { return true }
let xcodeThemeFileUpdated = {
guard let xcodeThemeModifiedDate = try? xcodeThemeURL
.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
else { return true }
return xcodeThemeModifiedDate.timeIntervalSince1970 > lastSyncTimestamp
}()
if xcodeThemeFileUpdated { return true }
return false
}()
if shouldSync {
Logger.service.info("Syncing Xcode theme: \(xcodeThemeName)")
do {
let theme = try XcodeTheme(fileURL: xcodeThemeURL)
let highlightrTheme = theme.asHighlightJSTheme()
try highlightrTheme.write(to: targetThemeURL, atomically: true, encoding: .utf8)
Task { @MainActor in
if light {
UserDefaults.shared.set(xcodeThemeName, for: \.lightXcodeThemeName)
UserDefaults.shared.set(.init(theme), for: \.lightXcodeTheme)
UserDefaults.shared.set(
.init(theme.plainTextColor.storable),
for: \.codeForegroundColorLight
)
UserDefaults.shared.set(
.init(theme.backgroundColor.storable),
for: \.codeBackgroundColorLight
)
UserDefaults.shared.set(
.init(theme.plainTextFont.storable),
for: \.codeFontLight
)
UserDefaults.shared.set(
.init(theme.currentLineColor.storable),
for: \.currentLineBackgroundColorLight
)
} else {
UserDefaults.shared.set(xcodeThemeName, for: \.darkXcodeThemeName)
UserDefaults.shared.set(.init(theme), for: \.darkXcodeTheme)
UserDefaults.shared.set(
.init(theme.plainTextColor.storable),
for: \.codeForegroundColorDark
)
UserDefaults.shared.set(
.init(theme.backgroundColor.storable),
for: \.codeBackgroundColorDark
)
UserDefaults.shared.set(
.init(theme.plainTextFont.storable),
for: \.codeFontDark
)
UserDefaults.shared.set(
.init(theme.currentLineColor.storable),
for: \.currentLineBackgroundColorDark
)
}
}
} catch {
Logger.service.error("Failed to sync Xcode theme \"\(xcodeThemeName)\": \(error)")
}
}
}
func locateXcodeTheme(named name: String) -> URL? {
if let customThemeURL = FileManager.default.urls(
for: .libraryDirectory,
in: .userDomainMask
).first?.appendingPathComponent("Developer/Xcode/UserData/FontAndColorThemes")
.appendingPathComponent(name),
FileManager.default.fileExists(atPath: customThemeURL.path)
{
return customThemeURL
}
let xcodeURL: URL? = {
// Use the latest running Xcode
if let running = XcodeInspector.shared.latestActiveXcode?.bundleURL {
return running
}
// Use the main Xcode.app
let proposedXcodeURL = URL(fileURLWithPath: "/Applications/Xcode.app")
if FileManager.default.fileExists(atPath: proposedXcodeURL.path) {
return proposedXcodeURL
}
// Look for an Xcode.app
if let applicationsURL = FileManager.default.urls(
for: .applicationDirectory,
in: .localDomainMask
).first {
struct InfoPlist: Codable {
var CFBundleIdentifier: String
}
let appBundleIdentifier = "com.apple.dt.Xcode"
let appDirectories = try? FileManager.default.contentsOfDirectory(
at: applicationsURL,
includingPropertiesForKeys: [],
options: .skipsHiddenFiles
)
for appDirectoryURL in appDirectories ?? [] {
let infoPlistURL = appDirectoryURL.appendingPathComponent("Contents/Info.plist")
if let data = try? Data(contentsOf: infoPlistURL),
let infoPlist = try? PropertyListDecoder().decode(
InfoPlist.self,
from: data
),
infoPlist.CFBundleIdentifier == appBundleIdentifier
{
return appDirectoryURL
}
}
}
return nil
}()
if let url = xcodeURL?
.appendingPathComponent("Contents/SharedFrameworks/DVTUserInterfaceKit.framework")
.appendingPathComponent("Versions/A/Resources/FontAndColorThemes")
.appendingPathComponent(name),
FileManager.default.fileExists(atPath: url.path)
{
return url
}
return nil
}
func createSupportDirectoriesIfNeeded() -> (supportDirectory: URL, themeDirectory: URL)? {
guard let supportURL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first?.appendingPathComponent(
Bundle.main
.object(forInfoDictionaryKey: "APPLICATION_SUPPORT_FOLDER") as! String
) else {
Logger.service.error("Could not determine support directory for Xcode theme synching")
return nil
}
let themeURL = supportURL.appendingPathComponent("Themes")
do {
if !FileManager.default.fileExists(atPath: supportURL.path) {
try FileManager.default.createDirectory(
at: supportURL,
withIntermediateDirectories: true,
attributes: nil
)
}
if !FileManager.default.fileExists(atPath: themeURL.path) {
try FileManager.default.createDirectory(
at: themeURL,
withIntermediateDirectories: true,
attributes: nil
)
}
} catch {
Logger.service.error("Failed to create support directories for Xcode theme synching: \(error)")
return nil
}
return (supportURL, themeURL)
}
}