-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathConfigManager.swift
More file actions
370 lines (330 loc) · 13 KB
/
ConfigManager.swift
File metadata and controls
370 lines (330 loc) · 13 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
import Foundation
import SwiftUI
import TOMLDecoder
final class ConfigManager: ObservableObject {
static let shared = ConfigManager()
@Published private(set) var config = Config()
@Published private(set) var initError: String?
private var fileWatchSource: DispatchSourceFileSystemObject?
private var fileDescriptor: CInt = -1
private var configFilePath: String?
private var suppressNextReload = false
private init() {
loadOrCreateConfigIfNeeded()
}
private func loadOrCreateConfigIfNeeded() {
let homePath = FileManager.default.homeDirectoryForCurrentUser.path
let path1 = "\(homePath)/.barik-config.toml"
let path2 = "\(homePath)/.config/barik/config.toml"
var chosenPath: String?
if FileManager.default.fileExists(atPath: path1) {
chosenPath = path1
} else if FileManager.default.fileExists(atPath: path2) {
chosenPath = path2
} else {
do {
try createDefaultConfig(at: path1)
chosenPath = path1
} catch {
initError = "Error creating default config: \(error.localizedDescription)"
print("Error when creating default config:", error)
return
}
}
if let path = chosenPath {
configFilePath = path
parseConfigFile(at: path)
startWatchingFile(at: path)
}
}
private func parseConfigFile(at path: String) {
do {
let content = try String(contentsOfFile: path, encoding: .utf8)
let decoder = TOMLDecoder()
let rootToml = try decoder.decode(RootToml.self, from: content)
DispatchQueue.main.async {
self.config = Config(rootToml: rootToml)
}
} catch {
initError = "Error parsing TOML file: \(error.localizedDescription)"
print("Error when parsing TOML file:", error)
}
}
private func createDefaultConfig(at path: String) throws {
let defaultTOML = """
# If you installed yabai or aerospace without using Homebrew,
# manually set the path to the binary. For example:
#
# yabai.path = "/run/current-system/sw/bin/yabai"
# aerospace.path = ...
theme = "system" # system, light, dark
[widgets]
displayed = [ # widgets on menu bar
"default.spaces",
"spacer",
"default.claude-usage",
"default.nowplaying",
"default.network",
"default.battery",
"default.countdown",
"divider",
# { "default.time" = { time-zone = "America/Los_Angeles", format = "E d, hh:mm" } },
"default.time"
]
[widgets.default.spaces]
space.show-key = true # show space number (or character, if you use AeroSpace)
window.show-title = true
window.title.max-length = 50
[widgets.default.claude-usage]
plan = "pro"
five-hour-limit = 80
weekly-limit = 500
[widgets.default.battery]
show-percentage = true
warning-level = 30
critical-level = 10
[widgets.default.time]
format = "E d, J:mm"
calendar.format = "J:mm"
calendar.show-events = true
# calendar.allow-list = ["Home", "Personal"] # show only these calendars
# calendar.deny-list = ["Work", "Boss"] # show all calendars except these
[popup.default.time]
view-variant = "box"
[background]
enabled = true
"""
try defaultTOML.write(toFile: path, atomically: true, encoding: .utf8)
}
private func startWatchingFile(at path: String) {
fileDescriptor = open(path, O_EVTONLY)
if fileDescriptor == -1 { return }
fileWatchSource = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: fileDescriptor, eventMask: .write,
queue: DispatchQueue.global())
fileWatchSource?.setEventHandler { [weak self] in
guard let self = self, let path = self.configFilePath else {
return
}
if self.suppressNextReload {
self.suppressNextReload = false
return
}
self.parseConfigFile(at: path)
}
fileWatchSource?.setCancelHandler { [weak self] in
if let fd = self?.fileDescriptor, fd != -1 {
close(fd)
}
}
fileWatchSource?.resume()
}
func updateConfigValue(key: String, newValue: String) {
guard let path = configFilePath else {
print("Config file path is not set")
return
}
do {
let currentText = try String(contentsOfFile: path, encoding: .utf8)
let updatedText = updatedTOMLString(
original: currentText, key: key, newValue: newValue, quoteValue: true)
try updatedText.write(
toFile: path, atomically: false, encoding: .utf8)
DispatchQueue.main.async {
self.parseConfigFile(at: path)
}
} catch {
print("Error updating config:", error)
}
}
func updateConfigValueRaw(key: String, newValue: String) {
guard let path = configFilePath else {
print("Config file path is not set")
return
}
do {
let currentText = try String(contentsOfFile: path, encoding: .utf8)
let updatedText = updatedTOMLString(
original: currentText, key: key, newValue: newValue, quoteValue: false)
try updatedText.write(
toFile: path, atomically: false, encoding: .utf8)
DispatchQueue.main.async {
self.parseConfigFile(at: path)
}
} catch {
print("Error updating config:", error)
}
}
private func updatedTOMLString(
original: String, key: String, newValue: String, quoteValue: Bool = true
) -> String {
let formattedValue = quoteValue ? "\"\(newValue)\"" : newValue
if key.contains(".") {
let components = key.split(separator: ".").map(String.init)
guard components.count >= 2 else {
return original
}
let tablePath = components.dropLast().joined(separator: ".")
let actualKey = components.last!
let tableHeader = "[\(tablePath)]"
let lines = original.components(separatedBy: "\n")
var newLines: [String] = []
var insideTargetTable = false
var updatedKey = false
var foundTable = false
for line in lines {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.hasPrefix("[") && trimmed.hasSuffix("]") {
if insideTargetTable && !updatedKey {
newLines.append("\(actualKey) = \(formattedValue)")
updatedKey = true
}
if trimmed == tableHeader {
foundTable = true
insideTargetTable = true
} else {
insideTargetTable = false
}
newLines.append(line)
} else {
if insideTargetTable && !updatedKey {
let pattern =
"^\(NSRegularExpression.escapedPattern(for: actualKey))\\s*="
if line.range(of: pattern, options: .regularExpression)
!= nil
{
newLines.append("\(actualKey) = \(formattedValue)")
updatedKey = true
continue
}
}
newLines.append(line)
}
}
if foundTable && insideTargetTable && !updatedKey {
newLines.append("\(actualKey) = \(formattedValue)")
}
if !foundTable {
newLines.append("")
newLines.append("[\(tablePath)]")
newLines.append("\(actualKey) = \(formattedValue)")
}
return newLines.joined(separator: "\n")
} else {
let lines = original.components(separatedBy: "\n")
var newLines: [String] = []
var updatedAtLeastOnce = false
for line in lines {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if !trimmed.hasPrefix("#") {
let pattern =
"^\(NSRegularExpression.escapedPattern(for: key))\\s*="
if line.range(of: pattern, options: .regularExpression)
!= nil
{
newLines.append("\(key) = \(formattedValue)")
updatedAtLeastOnce = true
continue
}
}
newLines.append(line)
}
if !updatedAtLeastOnce {
newLines.append("\(key) = \(formattedValue)")
}
return newLines.joined(separator: "\n")
}
}
func updateDisplayedWidgets(_ items: [TomlWidgetItem]) {
guard let path = configFilePath else {
print("Config file path is not set")
return
}
do {
let currentText = try String(contentsOfFile: path, encoding: .utf8)
let updatedText = replaceDisplayedArray(in: currentText, with: items)
suppressNextReload = true
try updatedText.write(toFile: path, atomically: true, encoding: .utf8)
DispatchQueue.main.async {
self.parseConfigFile(at: path)
}
} catch {
suppressNextReload = false
print("Error updating displayed widgets:", error)
}
}
private func replaceDisplayedArray(in original: String, with items: [TomlWidgetItem]) -> String {
let lines = original.components(separatedBy: "\n")
var inWidgetsSection = false
var arrayStartLine: Int?
var arrayEndLine: Int?
var bracketDepth = 0
var foundStart = false
for (lineIndex, line) in lines.enumerated() {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.hasPrefix("[") && trimmed.hasSuffix("]") {
inWidgetsSection = (trimmed == "[widgets]")
if foundStart && !inWidgetsSection {
break
}
continue
}
if inWidgetsSection && !foundStart {
if trimmed.hasPrefix("displayed") && trimmed.contains("=") {
arrayStartLine = lineIndex
foundStart = true
for char in trimmed {
if char == Character("[") { bracketDepth += 1 }
if char == Character("]") { bracketDepth -= 1 }
}
if bracketDepth == 0 {
arrayEndLine = lineIndex
break
}
}
} else if foundStart && arrayEndLine == nil {
for char in trimmed {
if char == Character("[") { bracketDepth += 1 }
if char == Character("]") { bracketDepth -= 1 }
}
if bracketDepth == 0 {
arrayEndLine = lineIndex
break
}
}
}
guard let start = arrayStartLine, let end = arrayEndLine else {
return original
}
let newArrayLines = "displayed = " + items.toTomlDisplayedArray()
var newLines = Array(lines[0..<start])
newLines.append(newArrayLines)
if end + 1 < lines.count {
newLines.append(contentsOf: lines[(end + 1)...])
}
return newLines.joined(separator: "\n")
}
func toggleWidget(_ widgetId: String) {
var items = config.rootToml.widgets.displayed
if let index = items.firstIndex(where: { $0.id == widgetId }) {
items.remove(at: index)
} else {
items.append(TomlWidgetItem(id: widgetId, inlineParams: [:]))
}
updateDisplayedWidgets(items)
}
func globalWidgetConfig(for widgetId: String) -> ConfigData {
config.rootToml.widgets.config(for: widgetId) ?? [:]
}
func resolvedWidgetConfig(for item: TomlWidgetItem) -> ConfigData {
let global = globalWidgetConfig(for: item.id)
if item.inlineParams.isEmpty {
return global
}
var merged = global
for (key, value) in item.inlineParams {
merged[key] = value
}
return merged
}
}