Repository navigation
Expand file tree
/
Copy pathSettingsStore.swift
More file actions
373 lines (332 loc) · 13.6 KB
/
Copy pathSettingsStore.swift
File metadata and controls
373 lines (332 loc) · 13.6 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
import AppKit
import Foundation
import ServiceManagement
@MainActor
final class SettingsStore: ObservableObject {
static let shared = SettingsStore()
@Published var language: AppLanguage {
didSet {
L10n.language = language
persist()
}
}
@Published var refreshSeconds: Double { didSet { persist() } }
@Published var showUnsigned: Bool { didSet { persist() } }
@Published var showMenuBarPercent: Bool { didSet { persist() } }
@Published var widgetEnabled: Bool {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var placement: WidgetPlacement {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var layout: WidgetLayout {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var dismissOutside: Bool { didSet { persist() } }
@Published var widgetScale: Double {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var edgeInset: Double {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var showRingPercent: Bool {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var positionLocked: Bool {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var snapToEdges: Bool { didSet { persist() } }
@Published var useCustomOrigin: Bool { didSet { persist() } }
@Published var customX: Double { didSet { persist() } }
@Published var customY: Double { didSet { persist() } }
@Published var widgetOpacity: Double {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var showRemaining: Bool {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var usageAlerts: Bool {
didSet {
persist()
if usageAlerts { UsageAlerts.request() }
}
}
@Published var showPace: Bool { didSet { persist() } }
@Published var autoHide: Bool {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageLayoutChanged, object: nil)
}
}
@Published var hotkeyWidget: KeyCombo? {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageHotkeysChanged, object: nil)
}
}
@Published var hotkeyDetail: KeyCombo? {
didSet {
persist()
NotificationCenter.default.post(name: .checkUsageHotkeysChanged, object: nil)
}
}
@Published var enabled: [ProviderID: Bool]
@Published var openRouterKey: String
@Published var deepSeekKey: String
@Published var zaiKey: String
private var ready = false
private var saveWork: DispatchWorkItem?
private var alerted: [String: Bool]
private var watches: [String: CycleWatch]
private let defaults = UserDefaults.standard
private init() {
let snapshot = SettingsFile.load() ?? Self.migrateFromDefaults()
language = AppLanguage(rawValue: snapshot.language) ?? .system
refreshSeconds = snapshot.refreshSeconds
showUnsigned = snapshot.showUnsigned
showMenuBarPercent = snapshot.showMenuBarPercent
widgetEnabled = snapshot.widgetEnabled
placement = WidgetPlacement(rawValue: snapshot.placement) ?? .topTrailing
layout = WidgetLayout(rawValue: snapshot.layout) ?? .vertical
dismissOutside = snapshot.dismissOutside
widgetScale = snapshot.widgetScale
edgeInset = snapshot.edgeInset
showRingPercent = snapshot.showRingPercent
positionLocked = snapshot.positionLocked
snapToEdges = snapshot.snapToEdges
useCustomOrigin = snapshot.useCustomOrigin
customX = snapshot.customX
customY = snapshot.customY
widgetOpacity = snapshot.widgetOpacity
showRemaining = snapshot.showRemaining
usageAlerts = snapshot.usageAlerts
showPace = snapshot.showPace
autoHide = snapshot.autoHide
hotkeyWidget = snapshot.hotkeyWidget ?? .defaultWidget
hotkeyDetail = snapshot.hotkeyDetail ?? .defaultDetail
alerted = snapshot.alerted
watches = snapshot.watches
var map: [ProviderID: Bool] = [:]
for id in ProviderID.allCases {
map[id] = snapshot.enabled[id.rawValue] ?? id.defaultEnabled
}
enabled = map
openRouterKey = SecretStore.appSecret(account: "openrouter") ?? ProcessInfo.processInfo.environment["OPENROUTER_API_KEY"] ?? ""
deepSeekKey = SecretStore.appSecret(account: "deepseek") ?? ProcessInfo.processInfo.environment["DEEPSEEK_API_KEY"] ?? ""
zaiKey = SecretStore.appSecret(account: "zai") ?? ProcessInfo.processInfo.environment["ZAI_API_KEY"] ?? ""
L10n.language = language
ready = true
if SettingsFile.load() == nil {
writeNow()
}
if snapshot.launchAtLogin != (SMAppService.mainApp.status == .enabled) {
launchAtLogin = snapshot.launchAtLogin
}
}
func isEnabled(_ id: ProviderID) -> Bool {
enabled[id] ?? true
}
func setEnabled(_ id: ProviderID, _ value: Bool) {
enabled[id] = value
persist()
}
func rememberCustomOrigin(_ point: CGPoint) {
useCustomOrigin = true
customX = point.x
customY = point.y
}
func clearCustomOrigin() {
useCustomOrigin = false
}
func wasAlerted(_ provider: ProviderID, level: Int, cycleEnd: Date?) -> Bool {
alerted[alertKey(provider, level: level, cycleEnd: cycleEnd)] == true
}
func markAlerted(_ provider: ProviderID, level: Int, cycleEnd: Date?) {
alerted[alertKey(provider, level: level, cycleEnd: cycleEnd)] = true
persist()
}
func clearAlerts(ifPercentBelow threshold: Double, provider: ProviderID, cycleEnd: Date?) {
if threshold < 65 {
alerted.removeValue(forKey: alertKey(provider, level: 70, cycleEnd: cycleEnd))
alerted.removeValue(forKey: alertKey(provider, level: 90, cycleEnd: cycleEnd))
persist()
} else if threshold < 85 {
alerted.removeValue(forKey: alertKey(provider, level: 90, cycleEnd: cycleEnd))
persist()
}
}
func persistKeys() {
SecretStore.setAppSecret(account: "openrouter", secret: openRouterKey.trimmingCharacters(in: .whitespacesAndNewlines))
SecretStore.setAppSecret(account: "deepseek", secret: deepSeekKey.trimmingCharacters(in: .whitespacesAndNewlines))
SecretStore.setAppSecret(account: "zai", secret: zaiKey.trimmingCharacters(in: .whitespacesAndNewlines))
}
var settingsFilePath: String {
SettingsFile.url.path
}
func revealSettingsFile() {
let folder = SettingsFile.url.deletingLastPathComponent()
try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
if !FileManager.default.fileExists(atPath: SettingsFile.url.path) {
writeNow()
}
NSWorkspace.shared.activateFileViewerSelecting([SettingsFile.url])
}
var launchAtLogin: Bool {
get { SMAppService.mainApp.status == .enabled }
set {
do {
if newValue { try SMAppService.mainApp.register() }
else { try SMAppService.mainApp.unregister() }
} catch {}
persist()
objectWillChange.send()
}
}
private func alertKey(_ provider: ProviderID, level: Int, cycleEnd: Date?) -> String {
let stamp = cycleEnd.map { String(Int($0.timeIntervalSince1970 / 3600)) } ?? "0"
return "\(provider.rawValue).\(level).\(stamp)"
}
private func persist() {
guard ready else { return }
saveWork?.cancel()
let work = DispatchWorkItem { [weak self] in
Task { @MainActor in self?.writeNow() }
}
saveWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: work)
}
private func writeNow() {
try? SettingsFile.save(snapshot())
}
func snapshot() -> SettingsSnapshot {
var enabledRaw: [String: Bool] = [:]
for (id, value) in enabled {
enabledRaw[id.rawValue] = value
}
return SettingsSnapshot(
version: 1,
language: language.rawValue,
refreshSeconds: refreshSeconds,
showUnsigned: showUnsigned,
showMenuBarPercent: showMenuBarPercent,
widgetEnabled: widgetEnabled,
placement: placement.rawValue,
layout: layout.rawValue,
dismissOutside: dismissOutside,
widgetScale: widgetScale,
edgeInset: edgeInset,
showRingPercent: showRingPercent,
positionLocked: positionLocked,
snapToEdges: snapToEdges,
useCustomOrigin: useCustomOrigin,
customX: customX,
customY: customY,
widgetOpacity: widgetOpacity,
showRemaining: showRemaining,
usageAlerts: usageAlerts,
launchAtLogin: SMAppService.mainApp.status == .enabled,
enabled: enabledRaw,
hotkeyWidget: hotkeyWidget,
hotkeyDetail: hotkeyDetail,
alerted: alerted,
watches: watches,
showPace: showPace,
autoHide: autoHide
)
}
func noteUsage(_ snapshot: QuotaSnapshot) {
guard let window = snapshot.forecastWindow else { return }
let end = window.resetsAt ?? snapshot.cycleEnd
guard let end else { return }
let key = "\(snapshot.provider.rawValue).\(window.id)"
let endTs = end.timeIntervalSince1970
if let existing = watches[key], abs(existing.cycleEnd - endTs) < 2 * 86400 {
return
}
watches[key] = CycleWatch(
cycleEnd: endTs,
firstAt: Date().timeIntervalSince1970,
firstPercent: window.clampedPercent
)
persist()
}
func watch(for snapshot: QuotaSnapshot) -> CycleWatch? {
guard let window = snapshot.forecastWindow else { return nil }
return watches["\(snapshot.provider.rawValue).\(window.id)"]
}
private static func migrateFromDefaults() -> SettingsSnapshot {
let defaults = UserDefaults.standard
var enabled: [String: Bool] = [:]
for id in ProviderID.allCases {
if defaults.object(forKey: "enabled.\(id.rawValue)") != nil {
enabled[id.rawValue] = defaults.bool(forKey: "enabled.\(id.rawValue)")
}
}
var alerted: [String: Bool] = [:]
for id in ProviderID.allCases {
for level in [70, 90] {
let key = "alerted.\(id.rawValue).\(level)"
if defaults.bool(forKey: key) {
alerted["\(id.rawValue).\(level)"] = true
}
}
}
return SettingsSnapshot(
language: defaults.string(forKey: "language") ?? AppLanguage.system.rawValue,
refreshSeconds: (defaults.object(forKey: "refreshSeconds") as? Double) ?? 60,
showUnsigned: defaults.object(forKey: "showUnsigned") as? Bool ?? false,
showMenuBarPercent: defaults.object(forKey: "showMenuBarPercent") as? Bool ?? true,
widgetEnabled: defaults.object(forKey: "widgetEnabled") as? Bool ?? true,
placement: defaults.string(forKey: "placement") ?? WidgetPlacement.topTrailing.rawValue,
layout: defaults.string(forKey: "layout") ?? WidgetLayout.vertical.rawValue,
dismissOutside: defaults.object(forKey: "dismissOutside") as? Bool ?? true,
widgetScale: defaults.object(forKey: "widgetScale") as? Double ?? 1,
edgeInset: defaults.object(forKey: "edgeInset") as? Double ?? 6,
showRingPercent: defaults.object(forKey: "showRingPercent") as? Bool ?? true,
positionLocked: defaults.object(forKey: "positionLocked") as? Bool ?? true,
snapToEdges: defaults.object(forKey: "snapToEdges") as? Bool ?? true,
useCustomOrigin: defaults.object(forKey: "useCustomOrigin") as? Bool ?? false,
customX: defaults.object(forKey: "customX") as? Double ?? 0,
customY: defaults.object(forKey: "customY") as? Double ?? 0,
widgetOpacity: defaults.object(forKey: "widgetOpacity") as? Double ?? 1,
showRemaining: defaults.object(forKey: "showRemaining") as? Bool ?? false,
usageAlerts: defaults.object(forKey: "usageAlerts") as? Bool ?? false,
launchAtLogin: SMAppService.mainApp.status == .enabled,
enabled: enabled,
hotkeyWidget: loadCombo(key: "hotkeyWidget") ?? .defaultWidget,
hotkeyDetail: loadCombo(key: "hotkeyDetail") ?? .defaultDetail,
alerted: alerted
)
}
private static func loadCombo(key: String) -> KeyCombo? {
guard let data = UserDefaults.standard.data(forKey: key) else { return nil }
return try? JSONDecoder().decode(KeyCombo.self, from: data)
}
}