forked from stappmus/Omarchy-Spotify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathService.qml
More file actions
4073 lines (3788 loc) · 145 KB
/
Copy pathService.qml
File metadata and controls
4073 lines (3788 loc) · 145 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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Services.Mpris
import "Api.js" as Api
// Shared state for the bar widget and the lazy full panel. MPRIS supplies local
// playback changes. External Spotify Connect playback is refreshed only while
// a UI is visible (or while a known remote item is actively playing).
Item {
id: root
visible: false
width: 0
height: 0
property var shell: null
property var manifest: null
property var pluginRegistry: null
readonly property string pluginId: manifest && manifest.id
? String(manifest.id) : "quickshell.spotify"
readonly property string pluginDir: manifest && manifest.__sourceDir
? String(manifest.__sourceDir) : ""
readonly property string homeDirectory: Quickshell.env("HOME") || ""
readonly property string stateHome: {
var explicit = String(Quickshell.env("XDG_STATE_HOME") || "").trim()
if (explicit) return explicit
return homeDirectory ? homeDirectory + "/.local/state" : ".local/state"
}
readonly property string stateDir: stateHome + "/omarchy-spotify"
readonly property string sessionPath: stateDir + "/session.json"
readonly property var defaultSettingValues: ({
deviceName: "Omarchy Spotify",
idleShutdownMinutes: 15,
showMiniPlayer: "On",
shortcutPlayer: "Omarchy Music app",
shortcutHints: "On",
showTrackTitle: "On",
showArtistName: "Off",
showPausedTrack: "On",
scrollBarText: "Off",
scrollSpeed: "1",
maxBarTextWidth: "240",
audioQuality: "320 kbps"
})
property var settings: Api.shallowCopy(defaultSettingValues)
readonly property string deviceName: String(settings.deviceName || "Omarchy Spotify").trim() || "Omarchy Spotify"
readonly property int idleShutdownMinutes: Math.max(0, Math.min(1440,
Math.floor(Number(settings.idleShutdownMinutes) || 0)))
readonly property bool showMiniPlayer: String(settings.showMiniPlayer || "On") !== "Off"
readonly property string shortcutPlayer: Api.normalizedShortcutPlayer(
settings.shortcutPlayer)
readonly property bool shortcutHintsEnabled: String(settings.shortcutHints || "On") !== "Off"
readonly property bool showTrackTitle: String(settings.showTrackTitle || "On") !== "Off"
readonly property bool showArtistName: String(settings.showArtistName || "Off") === "On"
readonly property bool showPausedTrack: String(settings.showPausedTrack || "On") !== "Off"
readonly property bool scrollBarText: String(settings.scrollBarText || "Off") === "On"
readonly property real scrollSpeed: Api.normalizedScrollSpeed(settings.scrollSpeed)
// Bar label cap in unscaled px; 0 means no cap.
readonly property real maxBarTextWidth: Api.normalizedMaxBarTextWidth(
settings.maxBarTextWidth)
readonly property int bitrateKbps: {
var quality = String(settings.audioQuality || "320 kbps")
return quality.indexOf("96") === 0 ? 96
: (quality.indexOf("160") === 0 ? 160 : 320)
}
readonly property string audioQuality: bitrateKbps + " kbps"
property var searchHistory: []
property var sessionState: ({})
property bool sessionFileReady: false
property bool sessionFileHadData: false
property bool sessionFileDirty: false
property bool pluginSessionKeysPendingStrip: false
readonly property alias auth: authManager
readonly property alias api: spotifyApi
readonly property alias daemon: daemonManager
readonly property alias backend: backendClient
readonly property bool accountConnected: authManager.loggedIn
readonly property bool sessionPending: !authManager.sessionChecked
readonly property bool fullyConnected: daemonManager.playbackReady
&& authManager.loggedIn && daemonManager.credentialsAvailable
readonly property bool loginBusy: daemonManager.setupBusy
|| authManager.loginBusy
|| authManager.sessionBusy || !authManager.sessionChecked
|| daemonManager.authenticationBusy || daemonManager.credentialsClearBusy
|| !daemonManager.credentialsChecked || !daemonManager.requirementsChecked
readonly property string loginProgress: loginProgressText()
readonly property var mprisPlayers: Mpris.players ? Mpris.players.values : []
readonly property var activePlayer: spotifydPlayer()
readonly property bool hasLocalPlayer: activePlayer !== null
property var remotePlayback: null
property bool remotePlaybackLoading: false
property var remotePlaybackWaiters: []
property var rememberedRemoteVolumeDevice: null
property real rememberedRemoteVolumePercent: -1
property var pendingRemoteSeek: null
property var pendingRemoteVolume: null
property real pendingSliderVolume: -1
property double pendingSliderUntil: 0
property bool volumeFlushQueued: false
property real queuedVolumeSlider: 0
property bool volumeFlushCooling: false
property bool volumeLiveActive: false
property int remoteControlSerial: 0
readonly property int remoteControlGraceMs: 8000
property string remoteVolumeProbeKey: ""
property int playbackPositionTick: 0
property string remoteControlDiscoveryKey: ""
readonly property var remoteTrack: remotePlayback ? remotePlayback.item : null
readonly property var currentArtists: remoteTrack
&& (useRemotePlayback || (currentTrackId !== ""
&& String(remoteTrack.id || "") === currentTrackId))
? Api.arrayValues(remoteTrack.artists) : []
readonly property bool currentArtistContextAvailable: Api.artistContextAvailable(
useRemotePlayback && remoteTrack ? remoteTrack.type : "",
currentTrackId, currentArtists)
readonly property bool currentAlbumContextAvailable: album !== ""
&& currentTrackId !== ""
readonly property var currentLyricsSong: Api.lyricsSong(currentTrackId,
title, artist, album, lengthSeconds, artUrl, positionSeconds)
readonly property bool lyricsAvailable: currentLyricsSong !== null
readonly property string lyricsPluginId: "stappmus.lyrics"
readonly property string lyricsPluginUrl: "https://github.com/stappmus/Omasing.git"
readonly property string lyricsPluginAvailability: {
var plugins = pluginRegistry && pluginRegistry.installedPlugins
? pluginRegistry.installedPlugins : ({})
var installed = !!plugins[lyricsPluginId]
var enabled = installed && pluginRegistry
&& typeof pluginRegistry.inBar === "function"
&& pluginRegistry.inBar(lyricsPluginId)
return Api.optionalPluginState(installed, enabled)
}
property bool lyricsPluginBusy: false
property string lyricsPluginOperation: ""
property string lyricsPluginError: ""
property string lyricsPluginRequestSurface: ""
property var pendingLyricsSong: null
property int lyricsPluginLaunchAttempts: 0
property double lyricsPluginInstallStartedAt: 0
readonly property var currentAlbumItem: remoteTrack
&& (useRemotePlayback || (currentTrackId !== ""
&& String(remoteTrack.id || "") === currentTrackId))
? remoteTrack.albumItem : null
readonly property var remoteDevice: remotePlayback ? remotePlayback.device : null
readonly property bool remotePlaybackIsLocal: !!remoteDevice
&& Api.isLocalPlaybackDevice(remoteDevice, deviceName,
localRuntimeDeviceName, localDeviceId)
readonly property bool useRemotePlayback: !!remotePlayback
&& !!remoteDevice && remoteDevice.active === true
&& !remotePlaybackIsLocal
&& !(hasLocalPlayer && activePlayer.isPlaying)
readonly property bool hasPlayer: useRemotePlayback || hasLocalPlayer
readonly property bool hasMedia: useRemotePlayback
? !!remoteTrack
: (hasLocalPlayer && !!(activePlayer.trackTitle || activePlayer.trackArtist))
readonly property bool playing: useRemotePlayback
? remotePlayback.playing === true
: (hasLocalPlayer && activePlayer.isPlaying)
readonly property int playbackState: hasPlayer
? (useRemotePlayback
? (remotePlayback.playing ? MprisPlaybackState.Playing : MprisPlaybackState.Paused)
: activePlayer.playbackState)
: MprisPlaybackState.Stopped
readonly property string title: useRemotePlayback && remoteTrack
? String(remoteTrack.name || "")
: (hasLocalPlayer ? String(activePlayer.trackTitle || "") : "")
readonly property string artist: useRemotePlayback && remoteTrack
? String(remoteTrack.subtitle || "")
: (hasLocalPlayer ? String(activePlayer.trackArtist || "") : "")
readonly property string album: useRemotePlayback && remoteTrack
? String(remoteTrack.album || "")
: (hasLocalPlayer ? String(activePlayer.trackAlbum || "") : "")
readonly property string artUrl: useRemotePlayback && remoteTrack
? String(remoteTrack.imageUrl || "")
: (hasLocalPlayer ? String(activePlayer.trackArtUrl || "") : "")
readonly property real positionSeconds: {
playbackPositionTick
if (!useRemotePlayback) return hasLocalPlayer && activePlayer.positionSupported
? Math.max(0, Number(activePlayer.position) || 0) : 0
var value = Api.displayedRemotePosition(remotePlayback,
pendingRemoteSeek, Date.now())
var maximum = remoteTrack ? Math.max(0, Number(remoteTrack.durationMs) || 0) / 1000 : 0
return maximum > 0 ? Math.min(maximum, value) : value
}
readonly property real lengthSeconds: useRemotePlayback && remoteTrack
? Math.max(0, Number(remoteTrack.durationMs) || 0) / 1000
: (hasLocalPlayer && activePlayer.lengthSupported
? Math.max(0, Number(activePlayer.length) || 0) : 0)
readonly property real playbackVolume: useRemotePlayback && remoteDevice
? displayedRemoteVolumePercent(remoteDevice) / 100
: (hasLocalPlayer && activePlayer.volumeSupported
? Math.max(0, Math.min(1, Number(activePlayer.volume) || 0)) : 0)
readonly property real reportedSliderVolume: useRemotePlayback
? playbackVolume : Api.spotifydVolumeToSlider(playbackVolume)
readonly property real volume: pendingSliderVolume >= 0
? pendingSliderVolume : reportedSliderVolume
readonly property bool volumePending: pendingSliderVolume >= 0
onReportedSliderVolumeChanged: reconcilePendingSliderVolume()
onUseRemotePlaybackChanged: {
clearPendingSliderVolume()
volumeFlushQueued = false
volumeFlushCooling = false
volumeLiveActive = false
if (volumeFlushTimer) volumeFlushTimer.stop()
if (volumeLiveIdleTimer) volumeLiveIdleTimer.stop()
}
readonly property bool shuffle: useRemotePlayback
? remotePlayback.shuffle === true
: (hasLocalPlayer && activePlayer.shuffleSupported
? activePlayer.shuffle === true : false)
readonly property string repeatMode: useRemotePlayback
? String(remotePlayback.repeatMode || "off") : mprisRepeatMode()
readonly property string currentUri: useRemotePlayback && remoteTrack
? String(remoteTrack.uri || "") : metadataString("xesam:url")
readonly property string currentExternalUrl: useRemotePlayback && remoteTrack
? String(remoteTrack.externalUrl || spotifyWebUrl(currentUri)) : spotifyWebUrl(currentUri)
readonly property string currentTrackId: {
// When a remote device owns playback, stale metadata from an idle local
// spotifyd player must not turn a podcast episode into a song.
if (useRemotePlayback) {
if (!remoteTrack || remoteTrack.type !== "track") return ""
return Api.spotifyTrackId(remoteTrack.uri)
|| String(remoteTrack.id || "").trim()
}
var id = Api.spotifyTrackId(currentUri)
if (id) return id
// spotifyd exposes the recording as an MPRIS object path such as
// /spotify/track/<id>, but does not currently publish xesam:url.
id = Api.spotifyTrackId(metadataString("mpris:trackid"))
if (id) return id
return remoteTrack && remotePlaybackIsLocal && remoteTrack.type === "track"
? String(remoteTrack.id || "").trim() : ""
}
readonly property var currentTrackItem: Api.currentPlaybackTrack(
currentTrackId, remoteTrack, title, artist, album, artUrl,
lengthSeconds, currentExternalUrl)
readonly property string currentTrackItemUri: currentTrackItem
? String(currentTrackItem.uri || "") : ""
readonly property bool currentTrackSaved: isSaved(currentTrackItem)
readonly property bool currentTrackSaveChecking: isSavedChecking(currentTrackItem)
readonly property bool currentTrackSaveBusy: currentTrackSaveChecking
|| isSavedBusy(currentTrackItem)
readonly property bool currentTrackSaveAvailable: !!currentTrackItem
&& authManager.loggedIn && !currentTrackSaveBusy
readonly property bool playbackRestricted: useRemotePlayback
&& remoteDevice && remoteDevice.restricted === true
readonly property var sonosControlDevice: findSonosControlDevice()
readonly property bool sonosControlAvailable: useRemotePlayback
&& playbackRestricted && !!sonosControlDevice
readonly property bool playbackControllable: hasPlayer
&& (!playbackRestricted || sonosControlAvailable)
readonly property bool volumeSupported: useRemotePlayback
? !!remoteDevice && remoteDevice.supportsVolume === true
&& (!playbackRestricted || sonosControlAvailable)
: (hasLocalPlayer && activePlayer.volumeSupported)
readonly property string playbackDeviceName: useRemotePlayback && remoteDevice
? Api.playbackDeviceDisplayName(remoteDevice, spotifyConnectManager.devices)
: (hasLocalPlayer ? deviceName : "")
property var playlists: []
property string playlistsNext: ""
property var savedTracks: []
property string savedTracksNext: ""
property var savedAlbums: []
property string savedAlbumsNext: ""
property var followedArtists: []
property string followedArtistsNext: ""
property var savedShows: []
property string savedShowsNext: ""
property var savedEpisodes: []
property string savedEpisodesNext: ""
property var savedAudiobooks: []
property string savedAudiobooksNext: ""
property var playlistItems: []
property string playlistItemsNext: ""
property string playlistItemsError: ""
property int playlistItemsStatus: 0
property int playlistItemsSerial: 0
property int playlistRestoreTargetCount: 0
property var selectedPlaylist: null
property string currentUserId: ""
property string currentUserName: ""
readonly property string playlistItemsEmptyMessage: Api.playlistItemsEmptyMessage(
selectedPlaylist, playlistItems.length, playlistItemsError,
playlistItemsStatus, currentUserId)
property var queue: []
property var devices: []
property var apiDevices: []
property string pendingDeviceLoadError: ""
property var deviceLoadWaiters: []
property bool pendingDeviceDiscover: false
property string selectedDeviceId: ""
property bool selectedDeviceExplicit: false
property string localDeviceId: ""
property string localRuntimeDeviceName: "Omarchy Spotify"
property string searchQuery: ""
property var searchGroups: Api.searchGroups({}, 128)
property var savedUris: ({})
property var savedUriCheckedAt: ({})
property var savedUriOrder: []
property var savedUrisChecking: ({})
property var savedUrisBusy: ({})
// The maps stay stable to avoid full copies; revisions keep QML lookups
// reactive when individual entries change.
property int savedUrisRevision: 0
property int savedUrisCheckingRevision: 0
property int savedUrisBusyRevision: 0
readonly property int savedUriCacheLimit: 4096
readonly property int savedUriFreshnessMs: 300000
property var recentTracks: []
property var topTracks: []
property var topArtists: []
property bool homeLoaded: false
property int homeRequestsPending: 0
readonly property bool homeLoading: homeRequestsPending > 0
property var discoverPlaylists: []
property var discoverCandidates: []
property bool discoverLoaded: false
property int discoverRequestsPending: 0
property int discoverRequestsFailed: 0
property int discoverSerial: 0
property string discoverMessage: ""
readonly property bool discoverLoading: discoverRequestsPending > 0
property var detailItem: null
property var detailItems: []
property string detailNext: ""
property bool detailLoading: false
property string detailMessage: ""
property int detailSerial: 0
property int detailRestoreTargetCount: 0
property var artistAlbums: []
property string artistAlbumsNext: ""
property bool artistAlbumsLoading: false
property var artistSongs: []
property string artistSongsNext: ""
property bool artistSongsLoading: false
property var artistPlaylists: []
property string artistPlaylistsNext: ""
property bool artistPlaylistsLoading: false
property var artistThisIsPlaylist: null
property bool artistThisIsLoading: false
property string artistCatalogQuery: ""
property int artistCatalogSerial: 0
readonly property bool artistCatalogLoading: artistAlbumsLoading
|| artistSongsLoading || artistPlaylistsLoading
property bool playlistActionBusy: false
property bool playlistConversionBusy: false
property string pendingPlaylistName: ""
property string sleepMode: "off"
property double sleepEndsAt: 0
property string sleepTrackUri: ""
readonly property bool sleepActive: sleepMode !== "off"
property int sleepRemainingSeconds: 0
property string activeView: "search"
property bool playlistsLoaded: false
property bool savedTracksLoaded: false
property bool savedAlbumsLoaded: false
property bool followedArtistsLoaded: false
property bool savedShowsLoaded: false
property bool savedEpisodesLoaded: false
property bool savedAudiobooksLoaded: false
property bool queueLoaded: false
property bool devicesLoaded: false
property bool playlistsLoading: false
property bool savedTracksLoading: false
property bool savedAlbumsLoading: false
property bool followedArtistsLoading: false
property bool savedShowsLoading: false
property bool savedEpisodesLoading: false
property bool savedAudiobooksLoading: false
property bool playlistItemsLoading: false
property bool queueLoading: false
property bool devicesLoading: false
property bool searchLoading: false
property string lastError: ""
property string statusMessage: ""
readonly property bool playlistRestorePending: Api.playlistRestorePending(
playlistItems.length, playlistRestoreTargetCount, playlistItemsLoading,
playlistItemsNext)
readonly property int playlistRememberedItemCount:
Api.normalizedPlaylistRestoreCount(Math.max(playlistItems.length,
playlistRestoreTargetCount))
readonly property bool detailRestorePending: !!detailItem
&& detailItem.type === "playlist" && Api.playlistRestorePending(
detailItems.length, detailRestoreTargetCount, detailLoading, detailNext)
readonly property int detailRememberedItemCount: Math.min(cacheLimit,
Api.normalizedPlaylistRestoreCount(Math.max(detailItems.length,
detailRestoreTargetCount)))
property int dataSerial: 0
property var visibleSurfaces: ({})
readonly property bool uiVisible: Object.keys(visibleSurfaces).length > 0
property double lastActivityAt: Date.now()
property var pendingPlayback: null
property var pendingPlaybackBody: null
property string pendingPlaybackMessage: ""
property var pendingPlaybackRadio: null
property int pendingPlaybackSerial: 0
property int radioSerial: 0
property var lastRadioPlaylist: null
property bool radioContextSelected: false
readonly property bool lastRadioPlaying: !!lastRadioPlaylist
&& radioContextSelected && playing
property bool localActivationRequested: false
property int deviceProbeAttempts: 0
property int localSocketWaitAttempts: 0
property int visibleLocalDeviceRefreshAttempts: 0
property bool loginFlowActive: false
property string pendingConnectDeviceId: ""
property int connectActivationAttempts: 0
property bool pendingConnectWakeTried: false
readonly property bool deviceActivationBusy: spotifyConnectManager.activating
|| (!!pendingConnectDeviceId && spotifyConnectManager.controlling)
|| connectAuthManager.loginBusy || connectAuthManager.sessionBusy
readonly property int cacheLimit: 200
signal operationFailed(string reason)
signal radioPlaylistReady(var playlist)
signal lyricsPluginPromptRequested(string surface, string availability)
signal lyricsPluginOpened(string surface)
function loginProgressText() {
if (daemonManager.setupBusy) return "Preparing playback on this computer"
if (daemonManager.credentialsClearBusy) return "Signing out"
if (authManager.loginBusy) return "Approve Spotify access in your browser"
if (authManager.sessionBusy || !authManager.sessionChecked)
return "Checking your saved Spotify session"
if (!daemonManager.requirementsChecked || !daemonManager.credentialsChecked)
return "Checking local playback"
if (daemonManager.authenticationBusy)
return "Approve local playback in your browser"
return fullyConnected ? "Connected to Spotify" : "Ready to connect"
}
function defaults() {
var fallback = Api.shallowCopy(defaultSettingValues)
var source = manifest && manifest.barWidget && manifest.barWidget.defaults
? manifest.barWidget.defaults : null
return source ? Api.assign(fallback, source) : fallback
}
function normalizedSettings(values) {
var next = defaults()
var source = values || {}
var keys = ["deviceName", "idleShutdownMinutes", "showMiniPlayer",
"shortcutPlayer", "shortcutHints", "showTrackTitle", "showArtistName",
"showPausedTrack", "scrollBarText", "scrollSpeed", "maxBarTextWidth",
"audioQuality"]
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
if (source[key] !== undefined) next[key] = source[key]
}
next.deviceName = String(next.deviceName || "Omarchy Spotify").trim() || "Omarchy Spotify"
next.idleShutdownMinutes = Math.max(0, Math.min(1440,
Math.floor(Number(next.idleShutdownMinutes) || 0)))
next.showMiniPlayer = String(next.showMiniPlayer || "On") === "Off" ? "Off" : "On"
next.shortcutPlayer = Api.normalizedShortcutPlayer(next.shortcutPlayer)
next.shortcutHints = Api.normalizedShortcutHints(next.shortcutHints)
next.showTrackTitle = String(next.showTrackTitle || "On") === "Off" ? "Off" : "On"
next.showArtistName = String(next.showArtistName || "Off") === "On" ? "On" : "Off"
next.showPausedTrack = String(next.showPausedTrack || "On") === "Off" ? "Off" : "On"
next.scrollBarText = String(next.scrollBarText || "Off") === "On" ? "On" : "Off"
if (!Api.canScrollBarText(next.showTrackTitle === "On", next.showArtistName === "On"))
next.scrollBarText = "Off"
next.scrollSpeed = String(Api.normalizedScrollSpeed(next.scrollSpeed))
next.maxBarTextWidth = String(Api.normalizedMaxBarTextWidth(next.maxBarTextWidth))
// An uncapped slot always fits its text, so the marquee could never run.
if (Number(next.maxBarTextWidth) === 0) next.scrollBarText = "Off"
var quality = String(next.audioQuality || "320 kbps")
next.audioQuality = quality.indexOf("96") === 0 ? "96 kbps"
: (quality.indexOf("160") === 0 ? "160 kbps" : "320 kbps")
return next
}
function relabelLocalDevices(source, previousName, nextName) {
var rows = Array.isArray(source) ? source : []
var result = []
for (var i = 0; i < rows.length; i++) {
var item = rows[i]
if (!item) continue
var local = item.local === true || Api.isLocalPlaybackDevice(item,
previousName, localRuntimeDeviceName, localDeviceId)
if (!local) {
result.push(item)
continue
}
var copy = Api.shallowCopy(item)
copy.name = nextName
copy.local = true
result.push(copy)
}
return result
}
function applySettings(values) {
var previousDeviceName = deviceName
var next = normalizedSettings(values)
if (JSON.stringify(next) !== JSON.stringify(settings)) settings = next
if (previousDeviceName !== next.deviceName) {
if (daemonManager.running && !localRuntimeDeviceName)
localRuntimeDeviceName = previousDeviceName
apiDevices = relabelLocalDevices(apiDevices, previousDeviceName, next.deviceName)
devices = relabelLocalDevices(devices, previousDeviceName, next.deviceName)
}
}
function persistSettings(values) {
var next = normalizedSettings(Api.assign(Api.shallowCopy(settings), values))
applySettings(next)
if (shell && typeof shell.updateEntryInline === "function")
shell.updateEntryInline(pluginId, next)
}
function persistSession(values) {
var next = Api.normalizedSessionState(values || ({}))
if (JSON.stringify(next) === JSON.stringify(sessionState)) return
sessionState = next
scheduleSessionSave()
}
function rememberSearch(term) {
var next = Api.touchHistory(searchHistory, term, 12)
if (JSON.stringify(next) === JSON.stringify(searchHistory)) return
searchHistory = next
scheduleSessionSave()
}
function clearSearchHistory() {
if (searchHistory.length === 0) return
searchHistory = []
scheduleSessionSave()
}
function currentSessionRecord() {
return Api.sessionRecord(sessionState, searchHistory)
}
function applySessionFile(raw) {
if (sessionFileReady) return
var fromFile = Api.parseSessionRecord(raw)
sessionFileHadData = !Api.sessionRecordIsEmpty(fromFile)
if (!sessionFileDirty && sessionFileHadData) {
sessionState = fromFile.sessionState
searchHistory = fromFile.searchHistory
}
sessionFileReady = true
reconcileSessionPersistence()
resumeLyricsInstallIntent()
}
function scheduleSessionSave() {
sessionFileDirty = true
if (sessionFileReady) sessionSaveTimer.restart()
}
function flushSessionFile() {
if (!sessionFileReady) return
sessionSaveTimer.stop()
sessionFile.setText(Api.encodeSessionRecord(sessionState, searchHistory))
}
function stripPluginSessionKeys() {
if (!pluginSessionKeysPendingStrip) return
var entry = configuredEntry()
if (!entry || !shell || typeof shell.updateEntryInline !== "function") return
pluginSessionKeysPendingStrip = false
persistSettings(entry)
}
function reconcileSessionPersistence() {
if (!sessionFileReady) return
var entry = configuredEntry() || {}
var pluginHasKeys = Api.pluginSettingsHaveSessionKeys(entry)
if (pluginHasKeys) {
if (Api.sessionRecordIsEmpty(currentSessionRecord()) && !sessionFileDirty) {
var fromPlugin = Api.sessionRecordFromPluginSettings(entry)
sessionState = fromPlugin.sessionState
searchHistory = fromPlugin.searchHistory
}
pluginSessionKeysPendingStrip = true
}
var shouldWrite = sessionFileDirty
|| (pluginHasKeys && !sessionFileHadData
&& !Api.sessionRecordIsEmpty(currentSessionRecord()))
if (shouldWrite) flushSessionFile()
else if (pluginHasKeys) stripPluginSessionKeys()
}
function configuredEntry() {
var config = shell && shell.shellConfig ? shell.shellConfig : null
if (!config) return null
var layout = config.bar && config.bar.layout ? config.bar.layout : null
var sections = ["left", "center", "right"]
if (layout) {
for (var s = 0; s < sections.length; s++) {
var rows = Array.isArray(layout[sections[s]]) ? layout[sections[s]] : []
for (var i = 0; i < rows.length; i++)
if (rows[i] && String(rows[i].id || "") === pluginId) return rows[i]
}
}
var plugins = Array.isArray(config.plugins) ? config.plugins : []
for (var p = 0; p < plugins.length; p++)
if (plugins[p] && String(plugins[p].id || "") === pluginId) return plugins[p]
return null
}
function syncSettings() {
applySettings(configuredEntry() || {})
reconcileSessionPersistence()
resumeLyricsInstallIntent()
}
function isSpotifyd(player) {
if (!player) return false
var identity = [player.dbusName, player.desktopEntry, player.identity]
.join(" ").toLowerCase()
return identity.indexOf("spotifyd") !== -1
|| identity.indexOf("librespot") !== -1
}
function spotifydPlayer() {
var fallback = null
for (var i = 0; i < mprisPlayers.length; i++) {
var player = mprisPlayers[i]
if (!isSpotifyd(player)) continue
if (player.isPlaying) return player
if (!fallback) fallback = player
}
return fallback
}
function metadataString(key) {
var metadata = activePlayer && activePlayer.metadata ? activePlayer.metadata : null
return metadata && metadata[key] !== undefined ? String(metadata[key]) : ""
}
function spotifyWebUrl(uri) {
var value = String(uri || "")
var match = value.match(/^spotify:(track|album|artist|playlist|episode|show|audiobook|chapter):([^:]+)$/)
return match ? "https://open.spotify.com/" + match[1] + "/" + match[2]
: (value.indexOf("https://open.spotify.com/") === 0 ? value : "")
}
function mprisRepeatMode() {
if (!hasLocalPlayer || !activePlayer.loopSupported) return "off"
if (activePlayer.loopState === MprisLoopState.Track) return "track"
if (activePlayer.loopState === MprisLoopState.Playlist) return "context"
return "off"
}
function safeError(reason) {
return Api.redact(String(reason || "Spotify operation failed"))
}
function fail(reason) {
statusClearTimer.stop()
lastError = safeError(reason)
statusMessage = ""
operationFailed(lastError)
}
function succeed(message) {
lastError = ""
statusMessage = String(message || "")
if (statusMessage) statusClearTimer.restart()
else statusClearTimer.stop()
}
function requestLyrics(surface) {
if (!currentLyricsSong) return "unavailable"
lyricsPluginRequestSurface = String(surface || "")
pendingLyricsSong = currentLyricsSong
lyricsPluginError = ""
lyricsPluginLaunchAttempts = 0
if (lyricsPluginAvailability === "ready") {
launchLyricsPlugin()
return "opening"
}
lyricsPluginPromptRequested(lyricsPluginRequestSurface,
lyricsPluginAvailability)
return lyricsPluginAvailability
}
function pendingLyricsInstall() {
var pending = sessionState && sessionState.pendingLyricsInstall
return pending && typeof pending === "object" ? pending : null
}
function persistLyricsInstallIntent() {
if (!pendingLyricsSong) return
var state = Api.shallowCopy(sessionState)
state.pendingLyricsInstall = Api.lyricsInstallIntent(pendingLyricsSong,
lyricsPluginRequestSurface, Date.now())
persistSession(state)
}
function clearLyricsInstallIntent() {
if (!pendingLyricsInstall()) return
persistSession(Api.sessionWithoutLyricsInstall(sessionState))
}
function confirmLyricsPlugin(surface) {
if (lyricsPluginBusy) return false
if (surface) lyricsPluginRequestSurface = String(surface)
if (!pendingLyricsSong) pendingLyricsSong = currentLyricsSong
if (!pendingLyricsSong) {
lyricsPluginError = "Play a song first, then try lyrics again."
return false
}
lyricsPluginError = ""
if (lyricsPluginAvailability === "ready") {
lyricsPluginLaunchAttempts = 0
launchLyricsPlugin()
return true
}
var command = Api.optionalPluginSetupCommand(lyricsPluginAvailability,
lyricsPluginId, lyricsPluginUrl)
if (!command.length) {
lyricsPluginError = "Omasing could not be prepared for installation."
return false
}
lyricsPluginOperation = lyricsPluginAvailability
lyricsPluginBusy = true
persistLyricsInstallIntent()
// Adding a plugin writes into ~/.config/omarchy/plugins, which reloads
// the shell and would kill a child Process before enable finishes.
// Detach the add and resume from the saved intent after reload.
if (lyricsPluginAvailability === "missing") {
lyricsPluginInstallStartedAt = Date.now()
Quickshell.execDetached(command)
lyricsPluginInstallPoll.restart()
return true
}
lyricsPluginSetupProcess.command = command
lyricsPluginSetupProcess.running = true
return true
}
function resumeLyricsInstallIntent() {
var intent = pendingLyricsInstall()
if (!intent) return
if (!Api.lyricsInstallIntentIsFresh(intent, Date.now(), 180000)) {
clearLyricsInstallIntent()
return
}
if (!pendingLyricsSong) pendingLyricsSong = intent.song
if (!lyricsPluginRequestSurface)
lyricsPluginRequestSurface = String(intent.surface || "")
if (lyricsPluginAvailability === "ready") {
lyricsPluginInstallPoll.stop()
lyricsPluginBusy = false
lyricsPluginError = ""
lyricsPluginLaunchAttempts = 0
clearLyricsInstallIntent()
launchLyricsPlugin()
return
}
if (lyricsPluginBusy || lyricsPluginSetupProcess.running
|| lyricsPluginInstallPoll.running)
return
if (lyricsPluginAvailability === "disabled") {
confirmLyricsPlugin(lyricsPluginRequestSurface)
return
}
lyricsPluginBusy = true
lyricsPluginOperation = "missing"
lyricsPluginInstallStartedAt = Number(intent.startedAt) || Date.now()
lyricsPluginInstallPoll.restart()
}
function finishLyricsPluginInstallWatch() {
if (lyricsPluginAvailability === "ready") {
lyricsPluginBusy = false
lyricsPluginError = ""
lyricsPluginLaunchAttempts = 0
clearLyricsInstallIntent()
launchLyricsPlugin()
return true
}
if (lyricsPluginAvailability === "disabled") {
lyricsPluginBusy = false
confirmLyricsPlugin(lyricsPluginRequestSurface)
return true
}
if (Date.now() - lyricsPluginInstallStartedAt < 90000) return false
lyricsPluginBusy = false
lyricsPluginError = "Omasing could not be installed. Check your network and try again."
clearLyricsInstallIntent()
lyricsPluginPromptRequested(lyricsPluginRequestSurface,
lyricsPluginAvailability)
return true
}
function cancelLyricsPlugin(surface) {
if (lyricsPluginBusy) return
if (surface && String(surface) !== lyricsPluginRequestSurface) return
lyricsPluginInstallPoll.stop()
lyricsPluginRequestSurface = ""
pendingLyricsSong = null
lyricsPluginError = ""
clearLyricsInstallIntent()
}
function launchLyricsPlugin() {
if (!pendingLyricsSong || lyricsPluginLaunchProcess.running) return
lyricsPluginLaunchAttempts++
lyricsPluginLaunchProcess.command = ["/usr/bin/omarchy-shell",
lyricsPluginId, "lyrics", JSON.stringify(pendingLyricsSong)]
lyricsPluginLaunchProcess.running = true
}
function finishLyricsPluginLaunch(exitCode) {
if (Number(exitCode) === 0) {
var openedSurface = lyricsPluginRequestSurface
pendingLyricsSong = null
lyricsPluginRequestSurface = ""
lyricsPluginError = ""
lyricsPluginLaunchAttempts = 0
lyricsPluginOpened(openedSurface)
return
}
if (lyricsPluginLaunchAttempts < 20) {
lyricsPluginLaunchRetry.restart()
return
}
var detail = String(lyricsPluginLaunchStderr.text || "").trim()
lyricsPluginError = safeError(detail
|| "Omasing is installed, but its lyrics window could not be opened.")
lyricsPluginPromptRequested(lyricsPluginRequestSurface,
lyricsPluginAvailability)
}
function noteActivity() {
lastActivityAt = Date.now()
}
function cancelVisibleLocalDeviceRefresh() {
visibleLocalDeviceRefreshTimer.stop()
visibleLocalDeviceRefreshAttempts = 0
}
function ensureVisibleLocalReceiver() {
var action = Api.visibleLocalReceiverAction(uiVisible,
fullyConnected && daemonManager.credentialsAvailable,
daemonManager.running, daemonManager.busy)
if (action === "idle") {
cancelVisibleLocalDeviceRefresh()
return
}
if (action === "start") daemonManager.start()
if (action === "refresh") visibleLocalDeviceRefreshAttempts = 0
visibleLocalDeviceRefreshTimer.restart()
}
function refreshVisibleLocalDevice() {
var action = Api.visibleLocalReceiverAction(uiVisible,
fullyConnected && daemonManager.credentialsAvailable,
daemonManager.running, daemonManager.busy)
if (action === "idle") {
cancelVisibleLocalDeviceRefresh()
return
}
if (action !== "refresh") {
if (action === "start") daemonManager.start()
visibleLocalDeviceRefreshTimer.restart()
return
}
loadDevices(function() {
if (!root.uiVisible || !root.fullyConnected || root.localDevice()) {
root.visibleLocalDeviceRefreshAttempts = 0
return
}
root.visibleLocalDeviceRefreshAttempts++
if (root.visibleLocalDeviceRefreshAttempts < 8)
visibleLocalDeviceRefreshTimer.restart()
})
}
function setUiVisible(key, value) {
var name = String(key || "surface")
var next = ({})
for (var oldKey in visibleSurfaces)
if (oldKey !== name && visibleSurfaces[oldKey]) next[oldKey] = true
if (value) next[name] = true
visibleSurfaces = next
if (value) {
noteActivity()
// SpotifyApi restores the keyring-backed session when needed. Do this for
// every opened surface so the mini-player can discover remote Spotify
// Connect playback without requiring the full panel to be opened first.
loadPlaybackState()
}
}
function refreshPosition() {
if (!useRemotePlayback && activePlayer && activePlayer.positionSupported)
activePlayer.positionChanged()
else playbackPositionTick++
}
function finishRemotePlaybackWaiters(ok) {
var pending = remotePlaybackWaiters.slice()
remotePlaybackWaiters = []
for (var i = 0; i < pending.length; i++) {
try { pending[i](ok === true) }
catch (e) { /* callers own callback errors */ }
}
}
function playbackDeviceKey(device) {
var item = device || {}
var id = String(item.id || "")
if (id) return "id:" + id
return "name:" + String(item.name || item.sourceName || "").trim().toLowerCase()
+ "|" + String(item.type || "").trim().toLowerCase()
}
function rememberRemoteVolume(device, value) {
var volumePercent = Api.normalizeVolumePercent(value)
if (!device || volumePercent === null) return false
rememberedRemoteVolumePercent = volumePercent
rememberedRemoteVolumeDevice = {
id: String(device.id || ""),
name: String(device.name || ""),
sourceName: String(device.sourceName || device.name || ""),
type: String(device.type || "")
}
return true
}
function displayedRemoteVolumePercent(device) {
if (Api.pendingRemoteVolumeShouldHold(device, pendingRemoteVolume,
Date.now()))
return Math.max(0, Math.min(100,
Number(pendingRemoteVolume.volumePercent) || 0))
if (rememberedRemoteVolumePercent >= 0 && rememberedRemoteVolumeDevice
&& Api.playbackDevicesMatch(rememberedRemoteVolumeDevice, device))
return rememberedRemoteVolumePercent
var reported = Api.normalizeVolumePercent((device || {}).volumePercent)
return reported === null ? 0 : reported
}
function rememberDiscoveredReceiverVolume(device) {
var receiver = findDiscoveredReceiver(device)
if (!receiver || String(receiver.brand || "").toLowerCase() !== "sonos")
return false
return rememberRemoteVolume(device, receiver.volumePercent)
}
function remoteControlDeviceSnapshot(device) {
var item = device || {}
return {
id: String(item.id || ""),
name: String(item.name || ""),
sourceName: String(item.sourceName || item.name || ""),
type: String(item.type || "")
}
}
function beginRemoteSeek(value) {
var serial = ++remoteControlSerial
pendingRemoteSeek = {
serial: serial,
device: remoteControlDeviceSnapshot(remoteDevice),
uri: String((remoteTrack && remoteTrack.uri) || ""),
positionSeconds: Math.max(0, Number(value) || 0),
requestedAt: Date.now(),
playing: remotePlayback && remotePlayback.playing === true,
expiresAt: Date.now() + remoteControlGraceMs
}
playbackPositionTick++
return serial
}