-
-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathKasetApp.swift
More file actions
458 lines (394 loc) · 17.5 KB
/
Copy pathKasetApp.swift
File metadata and controls
458 lines (394 loc) · 17.5 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
import AppKit
import SwiftUI
extension EnvironmentValues {
@Entry var searchFocusTrigger: Binding<Bool> = .constant(false)
}
extension EnvironmentValues {
@Entry var navigationSelection: Binding<NavigationItem?> = .constant(nil)
}
extension EnvironmentValues {
@Entry var showCommandBar: Binding<Bool> = .constant(false)
}
extension EnvironmentValues {
@Entry var showWhatsNew: Binding<Bool> = .constant(false)
}
// MARK: - KasetApp
/// Main entry point for the Kaset macOS application.
@available(macOS 26.0, *)
@main
struct KasetApp: App {
/// App delegate for lifecycle management (background playback).
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@State private var authService = AuthService()
@State private var webKitManager = WebKitManager.shared
@State private var playerService = PlayerService()
@State private var sharedClient: any YTMusicClientProtocol
@State private var notificationService: NotificationService?
@State private var updaterService = UpdaterService()
@State private var favoritesManager = FavoritesManager.shared
@State private var likeStatusManager = SongLikeStatusManager.shared
@State private var accountService: AccountService?
@State private var scrobblingCoordinator: ScrobblingCoordinator
@State private var syncedLyricsService: SyncedLyricsService
@State private var equalizerService = EqualizerService.shared
@State private var settings = SettingsManager.shared
@State private var boringNotchBridge: BoringNotchBridgeService?
/// Triggers search field focus when set to true.
@State private var searchFocusTrigger = false
/// Current navigation selection for keyboard navigation.
@State private var navigationSelection: NavigationItem? = SettingsManager.shared.launchNavigationItem
/// Whether the command bar is visible.
@State private var showCommandBar = false
/// Whether the "What's New" sheet should be shown.
@State private var showWhatsNew = false
init() {
Bundle.enableAppLocalizationOverride()
let auth = AuthService()
let webkit = WebKitManager.shared
let player = PlayerService()
// Use mock client in UI test mode, real client otherwise
let realClient = YTMusicClient(authService: auth, webKitManager: webkit)
let client: YTMusicClientProtocol = if UITestConfig.isUITestMode {
MockUITestYTMusicClient()
} else {
realClient
}
// Wire up dependencies
player.setYTMusicClient(client)
SongLikeStatusManager.shared.setClient(client)
// Set shared instance for AppleScript access
PlayerService.shared = player
// Create account service
let account = AccountService(ytMusicClient: client, authService: auth)
// Wire up brand account provider so API requests use the correct account
realClient.brandIdProvider = { [weak account] in
account?.currentBrandId
}
_authService = State(initialValue: auth)
_webKitManager = State(initialValue: webkit)
_playerService = State(initialValue: player)
_sharedClient = State(initialValue: client)
_syncedLyricsService = State(initialValue: SyncedLyricsService(providers: [
YTMusicSyncedProvider(client: client),
LRCLibProvider(),
]))
_notificationService = State(initialValue: NotificationService(playerService: player))
_accountService = State(initialValue: account)
// Create scrobbling coordinator
let lastFMService = LastFMService(credentialStore: KeychainCredentialStore())
let scrobblingCoordinator = ScrobblingCoordinator(
playerService: player,
services: [lastFMService]
)
scrobblingCoordinator.restoreAuthState()
scrobblingCoordinator.startMonitoring()
_scrobblingCoordinator = State(initialValue: scrobblingCoordinator)
let boringNotchBridge = BoringNotchBridgeService(playerService: player)
_boringNotchBridge = State(initialValue: boringNotchBridge)
// Wire up PlayerService to AppDelegate immediately (not in onAppear)
// This ensures playerService is available for lifecycle events like queue restoration
self.appDelegate.playerService = player
if UITestConfig.isUITestMode {
DiagnosticsLogger.ui.info("App launched in UI Test mode")
}
}
var body: some Scene {
Window("Kaset", id: "main") {
// Skip UI during unit tests to prevent window spam
if UITestConfig.isRunningUnitTests, !UITestConfig.isUITestMode {
Color.clear
.frame(width: 1, height: 1)
} else {
MainWindow(navigationSelection: self.$navigationSelection, client: self.sharedClient)
.id(self.settings.contentLanguage)
.environment(\.locale, self.settings.contentLanguage.locale)
.environment(self.authService)
.environment(self.webKitManager)
.environment(self.playerService)
.environment(self.favoritesManager)
.environment(self.likeStatusManager)
.environment(self.accountService)
.environment(self.scrobblingCoordinator)
.environment(self.syncedLyricsService)
.environment(self.equalizerService)
.environment(\.searchFocusTrigger, self.$searchFocusTrigger)
.environment(\.navigationSelection, self.$navigationSelection)
.environment(\.showCommandBar, self.$showCommandBar)
.environment(\.showWhatsNew, self.$showWhatsNew)
.onAppear {
DiagnosticsLogger.app.info("KasetApp: App content appeared")
// Wire up PlayerService to AppDelegate for dock menu and AppleScript actions
// This runs synchronously so AppleScript commands can access playerService immediately
self.appDelegate.playerService = self.playerService
// Reference notificationService to keep SwiftUI from deallocating it
_ = self.notificationService
// Start boring.notch bridge if enabled
if self.settings.boringNotchBridgeEnabled {
DiagnosticsLogger.network.info("boring.notch integration enabled at launch; starting bridge")
self.boringNotchBridge?.start()
}
}
.task {
DiagnosticsLogger.app.info("KasetApp: Root task started")
// Check if user is already logged in from previous session
await self.authService.checkLoginStatus()
DiagnosticsLogger.app.info("KasetApp: Login status check complete")
// Fetch accounts after login check (for account switcher)
await self.accountService?.fetchAccounts()
// Warm up Foundation Models in background
await FoundationModelsService.shared.warmup()
}
.onOpenURL { url in
self.handleIncomingURL(url)
}
.onChange(of: self.playerService.isPlaying) { _, isPlaying in
// The Core Audio process tap needs WebKit's GPU
// process to be actively emitting audio before it
// can be discovered. When playback starts, give the
// equalizer a chance to spin up.
if isPlaying {
self.equalizerService.retryStartIfEnabled()
}
}
.onChange(of: self.settings.boringNotchBridgeEnabled) { _, enabled in
if enabled {
DiagnosticsLogger.network.info("boring.notch integration enabled from settings; starting bridge")
self.boringNotchBridge?.start()
} else {
DiagnosticsLogger.network.info("boring.notch integration disabled from settings; stopping bridge")
self.boringNotchBridge?.stop()
}
}
}
}
Settings {
SettingsView()
.environment(\.locale, self.settings.contentLanguage.locale)
.environment(self.authService)
.environment(self.updaterService)
.environment(self.scrobblingCoordinator)
.environment(self.equalizerService)
}
.commands {
// Check for Updates command in app menu
CommandGroup(after: .appInfo) {
Button("Check for Updates...") {
self.updaterService.checkForUpdates()
}
.disabled(!self.updaterService.canCheckForUpdates)
}
// Playback commands
CommandMenu("Playback") {
// Play/Pause - Space
Button(self.playerService.isPlaying ? "Pause" : "Play") {
Task {
await self.playerService.playPause()
}
}
.keyboardShortcut(.space, modifiers: [])
.disabled(self.playerService.currentTrack == nil && self.playerService.pendingPlayVideoId == nil)
Divider()
// Next Track - ⌘→
Button("Next") {
Task {
await self.playerService.next()
}
}
.keyboardShortcut(.rightArrow, modifiers: .command)
// Previous Track - ⌘←
Button("Previous") {
Task {
await self.playerService.previous()
}
}
.keyboardShortcut(.leftArrow, modifiers: .command)
Divider()
// Volume Up - ⌘↑
Button("Volume Up") {
Task {
await self.playerService.setVolume(min(1.0, self.playerService.volume + 0.1))
}
}
.keyboardShortcut(.upArrow, modifiers: .command)
// Volume Down - ⌘↓
Button("Volume Down") {
Task {
await self.playerService.setVolume(max(0.0, self.playerService.volume - 0.1))
}
}
.keyboardShortcut(.downArrow, modifiers: .command)
// Mute
Button(self.playerService.isMuted ? "Unmute" : "Mute") {
Task {
await self.playerService.toggleMute()
}
}
Divider()
// Shuffle - ⌘S
Button(self.playerService.shuffleEnabled ? "Shuffle Off" : "Shuffle On") {
self.playerService.toggleShuffle()
}
.keyboardShortcut("s", modifiers: .command)
// Repeat - ⌘R
Button(self.repeatModeLabel) {
self.playerService.cycleRepeatMode()
}
.keyboardShortcut("r", modifiers: .command)
Divider()
// Lyrics - ⌘L
Button(self.playerService.showLyrics ? "Hide Lyrics" : "Show Lyrics") {
withAnimation(.easeInOut(duration: 0.2)) {
self.playerService.showLyrics.toggle()
}
}
.keyboardShortcut("l", modifiers: .command)
}
// Navigation commands - replace default sidebar toggle
CommandGroup(replacing: .sidebar) {
// Home - ⌘1
Button("Home") {
self.navigationSelection = .home
}
.keyboardShortcut("1", modifiers: .command)
// Explore - ⌘2
Button("Explore") {
self.navigationSelection = .explore
}
.keyboardShortcut("2", modifiers: .command)
// Library - ⌘3
Button("Library") {
self.navigationSelection = .library
}
.keyboardShortcut("3", modifiers: .command)
Divider()
// Search - ⌘F
Button("Search") {
self.navigationSelection = .search
// Trigger focus after a brief delay to allow view to appear
Task { @MainActor in
try? await Task.sleep(for: .milliseconds(100))
self.searchFocusTrigger = true
}
}
.keyboardShortcut("f", modifiers: .command)
// Command Bar - ⌘K
Button("Command Bar") {
self.showCommandBar = true
}
.keyboardShortcut("k", modifiers: .command)
}
// Window menu - show main window
CommandGroup(after: .windowArrangement) {
Button("Kaset") {
self.showMainWindow()
}
.keyboardShortcut("0", modifiers: .command)
}
// Help menu - What's New
CommandGroup(after: .appInfo) {
Divider()
Button("What's New in Kaset") {
self.showWhatsNew = true
}
}
}
}
/// Shows the main window.
private func showMainWindow() {
// Find and show the main window
for window in NSApplication.shared.windows where window.frameAutosaveName == "KasetMainWindow" {
window.makeKeyAndOrderFront(nil)
NSApplication.shared.activate(ignoringOtherApps: true)
return
}
// Fallback: find any main-capable window that's not the video window
for window in NSApplication.shared.windows where window.canBecomeMain {
if window.identifier?.rawValue == AccessibilityID.VideoWindow.container {
continue
}
window.makeKeyAndOrderFront(nil)
NSApplication.shared.activate(ignoringOtherApps: true)
return
}
}
/// Label for repeat mode menu item.
private var repeatModeLabel: String {
switch self.playerService.repeatMode {
case .off:
"Repeat All"
case .all:
"Repeat One"
case .one:
"Repeat Off"
}
}
// MARK: - URL Handling
/// Handles an incoming URL (from custom scheme).
private func handleIncomingURL(_ url: URL) {
DiagnosticsLogger.app.info("Received URL: \(url.absoluteString)")
guard let content = URLHandler.parse(url) else {
DiagnosticsLogger.app.warning("Unrecognized URL format: \(url.absoluteString)")
return
}
// If not logged in, ignore for now
guard self.authService.state.isLoggedIn else {
DiagnosticsLogger.app.info("Not logged in, ignoring URL")
return
}
self.handleParsedContent(content)
}
/// Handles parsed URL content.
private func handleParsedContent(_ content: URLHandler.ParsedContent) {
switch content {
case let .song(videoId):
DiagnosticsLogger.app.info("Playing song from URL: \(videoId)")
let song = Song(
id: videoId,
title: "Loading...",
artists: [],
videoId: videoId
)
Task {
await self.playerService.play(song: song)
}
case .playlist, .album, .artist:
// Only song playback is supported via URL scheme
DiagnosticsLogger.app.info("URL scheme only supports song playback")
}
}
}
// MARK: - SettingsView
/// Main settings view with tabbed navigation.
@available(macOS 26.0, *)
struct SettingsView: View {
@Environment(UpdaterService.self) private var updaterService
@Environment(ScrobblingCoordinator.self) private var scrobblingCoordinator
var body: some View {
TabView {
GeneralSettingsView(updaterService: self.updaterService)
.tabItem {
Label("General", systemImage: "gearshape")
}
IntelligenceSettingsView()
.tabItem {
Label("Intelligence", systemImage: "sparkles")
}
ScrobblingSettingsView()
.environment(self.scrobblingCoordinator)
.tabItem {
Label("Scrobbling", systemImage: "music.note.list")
}
EqualizerSettingsView()
.tabItem {
Label("Equalizer", systemImage: "slider.vertical.3")
}
ExtensionsSettingsView()
.tabItem {
Label("Extensions", systemImage: "puzzlepiece.extension")
}
}
// 520×520 fits the Equalizer tab's six-band slider grid + curve
// preview; the other tabs grow comfortably into the extra space.
.frame(width: 520, height: 520)
}
}