-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathextension.js
More file actions
1118 lines (975 loc) · 44.8 KB
/
Copy pathextension.js
File metadata and controls
1118 lines (975 loc) · 44.8 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
/*
* Spotify Controls Extension
* Copyright (C) 2024 Athanasios Raptis
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import St from 'gi://St';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import Clutter from 'gi://Clutter';
import Pango from 'gi://Pango';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
import { Extension, gettext as _ } from 'resource:///org/gnome/shell/extensions/extension.js';
// Debugging flag and function to control debug logging
const DEBUG = false;
/**
* Logs debug messages to the GNOME Shell log if debugging is enabled.
* @param {string} message - The debug message to log.
*/
function logDebug(message) {
if (DEBUG) {
console.log(`[Spotify Controls DEBUG]: ${message}`);
}
}
/**
* Logs error messages to the GNOME Shell log.
* @param {Error} error - The error object.
* @param {string} message - Additional context for the error.
*/
function logError(error, message) {
console.error(`[Spotify Controls ERROR]: ${message}`, error);
}
// Define constants for Spotify's MPRIS D-Bus interface
const SPOTIFY_BUS_NAME = 'org.mpris.MediaPlayer2.spotify'; // D-Bus bus name for Spotify
const SPOTIFY_OBJECT_PATH = '/org/mpris/MediaPlayer2'; // Object path for Spotify's MPRIS interface
const MPRIS_PLAYER_INTERFACE = 'org.mpris.MediaPlayer2.Player'; // Interface for player controls
const PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'; // Interface for property changes
/**
* SpotifyIndicator Class
* Extends PanelMenu.Button to create a Spotify controls indicator in the GNOME top bar.
*/
var SpotifyIndicator = GObject.registerClass(
class SpotifyIndicator extends PanelMenu.Button {
/**
* Constructor for SpotifyIndicator.
* @param {string} extensionPath - The path to the extension's directory.
* @param {string} controlsPosition - Position of playback controls ('left' or 'right').
* @param {Gio.Settings} settings - The settings object for the extension.
*/
_init(extensionPath, controlsPosition, settings) {
super._init(0.0, 'Spotify Controls');
logDebug('SpotifyIndicator initialized');
this.controlsPosition = controlsPosition;
this._settings = settings;
this._signalSubscriptionId = null;
// Initialize the _activeTimeouts array
this._activeTimeouts = [];
// Track button-press-event connections so they can be explicitly
// disconnected on destroy().
this._buttonSignals = [];
// Store the extensionPath for later use
this.extensionPath = extensionPath;
this._buildUI(extensionPath);
this._monitorSpotifyPresence();
// Connect the 'button-press-event' to the updated handler
this.connect('button-press-event', this._onExtensionClicked.bind(this));
// Connect to changes in 'show-spotify-icon' and 'show-track-info' and 'max-width' settings
this._showIconChangedId = this._settings.connect('changed::show-spotify-icon', this._onShowIconChanged.bind(this));
this._showTrackInfoChangedId = this._settings.connect('changed::show-track-info', this._onShowTrackInfoChanged.bind(this));
this._maxWidthChangedId = this._settings.connect('changed::max-width', this._onMaxWidthChanged.bind(this));
}
/**
* Helper function to create a separator.
* @returns {St.Label} - A new St.Label instance acting as a separator.
*/
_createSeparator() {
return new St.Label({ text: ' ' });
}
/**
* Builds the user interface components of the Spotify indicator.
* @param {string} extensionPath - The path to the extension's directory.
*/
_buildUI(extensionPath) {
logDebug('Building UI');
// Create the main horizontal box layout for the indicator
let hbox = new St.BoxLayout({ style_class: 'spotify-hbox' });
this.add_child(hbox);
// Create a container for playback controls
let controlsBox = new St.BoxLayout({ style_class: 'spotify-controls-box' });
// Conditionally add playback controls based on the setting
if (this._settings.get_boolean('show-playback-controls')) {
// Create the control buttons: Previous, Play/Pause, Next
this.prevButton = new St.Button({
style_class: 'spotify-status-icon',
child: new St.Icon({ icon_name: 'media-skip-backward-symbolic' }),
});
this.playPauseButton = new St.Button({
style_class: 'spotify-status-icon',
child: new St.Icon({ icon_name: 'media-playback-pause-symbolic' }),
});
this.nextButton = new St.Button({
style_class: 'spotify-status-icon',
child: new St.Icon({ icon_name: 'media-skip-forward-symbolic' }),
});
// GNOME Shell 49/50 changed event dispatching for nested St.Button
// actors inside panel indicators, so the 'clicked' signal can stop
// firing. Use button-press-event directly via _connectActionButton.
this._connectActionButton(this.prevButton, () => this._sendMPRISCommand('Previous'));
this._connectActionButton(this.playPauseButton, () => this._sendMPRISCommand('PlayPause'));
this._connectActionButton(this.nextButton, () => this._sendMPRISCommand('Next'));
// Add buttons to the controlsBox
controlsBox.add_child(this.prevButton);
controlsBox.add_child(this.playPauseButton);
controlsBox.add_child(this.nextButton);
}
// Container to contain the track info and spotify logo
this.trackBox = new St.BoxLayout();
// Button to show and hide spotify window
this.trackButton = new St.Button({
child: this.trackBox
});
this._connectActionButton(
this.trackButton,
() => this._activateSpotifyWindow(),
() => this._handleMiddleClick()
);
// Spotify icon - Load the SVG from the icons directory using extensionPath
this.spotifyIcon = new St.Icon({
gicon: Gio.icon_new_for_string(`${extensionPath}/icons/spotify.svg`),
icon_size: 16,
style_class: 'spotify-icon',
});
// Initially set the visibility based on the settings
this.spotifyIcon.visible = this._settings.get_boolean('show-spotify-icon');
// Add the Spotify icon and separators to the UI
this.trackBox.add_child(this.spotifyIcon);
this.trackBox.add_child(this._createSeparator());
this.trackBox.add_child(this._createSeparator());
this.trackBox.add_child(this._createSeparator());
const maxWidth = this._settings.get_int('max-width');
// Artist and Song Title label
this.trackLabel = new St.Label({
text: _('No Track Playing'),
y_expand: true,
y_align: Clutter.ActorAlign.CENTER,
style: maxWidth ? `max-width: ${maxWidth}px;` : '',
});
// Display the track label with ellipsis if it exceeds the maximum width
this.trackLabel.clutter_text.ellipsize = Pango.EllipsizeMode.END;
// Conditionally display the track info based on the setting
this.trackLabel.visible = this._settings.get_boolean('show-track-info');
// add trackLabel to the UI
this.trackBox.add_child(this.trackLabel);
// Add scroll event listener to widget for volume control
if (this._settings.get_boolean('enable-volume-control')) {
this.connect('scroll-event', this._adjustVolume.bind(this));
}
// Based on controlsPosition, arrange the UI elements
if (this.controlsPosition === 'left') {
// Add playback controls first if they are enabled
if (this._settings.get_boolean('show-playback-controls')) {
hbox.add_child(controlsBox);
hbox.add_child(this._createSeparator());
hbox.add_child(this._createSeparator());
hbox.add_child(this._createSeparator());
}
hbox.add_child(this.trackButton);
} else {
// Add playback controls last (default behavior) if they are enabled
hbox.add_child(this.trackButton);
if (this._settings.get_boolean('show-playback-controls')) {
hbox.add_child(this._createSeparator());
hbox.add_child(this._createSeparator());
hbox.add_child(controlsBox);
}
}
logDebug('UI built with controls positioned to the ' + this.controlsPosition);
}
/**
* Callback function when the 'show-spotify-icon' setting changes.
* Shows or hides the Spotify icon based on the new setting.
*/
_onShowIconChanged() {
const showIcon = this._settings.get_boolean('show-spotify-icon');
logDebug(`'show-spotify-icon' changed to ${showIcon}`);
if (this.spotifyIcon) {
this.spotifyIcon.visible = showIcon;
logDebug(`Spotify icon visibility set to ${showIcon}`);
} else if (showIcon) {
// If for some reason the icon wasn't created, create and add it
this.spotifyIcon = new St.Icon({
gicon: Gio.icon_new_for_string(`${this.extensionPath}/icons/spotify.svg`),
icon_size: 16,
style_class: 'spotify-icon',
});
this.spotifyIcon.visible = showIcon;
// Add the Spotify icon to the UI
this.trackBox.add_child_before(this.spotifyIcon, this.trackButton);
this.trackBox.add_child_after(this.spotifyIcon, this._createSeparator());
this.trackBox.add_child_after(this.spotifyIcon, this._createSeparator());
this.trackBox.add_child_after(this.spotifyIcon, this._createSeparator());
logDebug('Spotify icon created and shown');
}
}
/**
* Callback function when the 'show-track-info' setting changes.
* Shows or hides the Artist/Track information based on the new setting.
*/
_onShowTrackInfoChanged() {
const showInfo = this._settings.get_boolean('show-track-info');
logDebug(`'show-track-info' changed to ${showInfo}`);
if (this.trackLabel) {
this.trackLabel.visible = showInfo;
logDebug(`Track info visibility set to ${showInfo}`);
}
}
_onMaxWidthChanged() {
const maxWidth = this._settings.get_int('max-width');
logDebug(`'max-width' changed to ${maxWidth}`);
this.trackLabel.style = `max-width: ${maxWidth}px;`;
logDebug(`Track label style set to ${this.trackLabel.style}`);
}
/**
* Connect a button action in a way that stays reliable on GNOME Shell
* 49/50, where the legacy 'clicked' signal can be swallowed for
* St.Button actors nested inside a PanelMenu.Button.
* @param {St.Button} button - The button actor.
* @param {Function} handler - Handler invoked on left click.
* @param {Function|null} middleHandler - Optional handler for middle click.
*/
_connectActionButton(button, handler, middleHandler = null) {
if (typeof button.clear_actions === 'function')
button.clear_actions();
const signalId = button.connect('button-press-event', (_actor, event) => {
const pressedButton = event.get_button();
if (pressedButton === Clutter.BUTTON_MIDDLE && middleHandler) {
try {
middleHandler();
} catch (e) {
logError(e, 'Failed to handle middle button press');
}
return Clutter.EVENT_STOP;
}
if (pressedButton !== Clutter.BUTTON_PRIMARY)
return Clutter.EVENT_PROPAGATE;
try {
handler();
} catch (e) {
logError(e, 'Failed to handle button press');
}
return Clutter.EVENT_STOP;
});
this._buttonSignals.push({ button, signalId });
}
/**
* Handles clicks on the extension's panel button itself (clicks that
* don't land on the trackButton or control buttons).
* @param {Clutter.Actor} actor - The actor that received the event.
* @param {Clutter.Event} event - The event object.
*/
_onExtensionClicked(actor, event) {
const button = event.get_button();
if (button === Clutter.BUTTON_MIDDLE)
this._handleMiddleClick();
}
_handleMiddleClick() {
const enableMiddleClick = this._settings.get_boolean('enable-middle-click');
if (!enableMiddleClick)
return;
this._sendMPRISCommand('PlayPause')
.catch(() => {
this._launchSpotify();
});
}
/**
* Activates (or minimizes) the Spotify window, depending on user preferences
* and the current window state.
*/
_activateSpotifyWindow() {
logDebug('Attempting to activate Spotify window');
// Retrieve the user setting for whether to minimize on second click
const minimizeOnSecondClick = this._settings.get_boolean('minimize-on-second-click');
logDebug(`minimizeOnSecondClick = ${minimizeOnSecondClick}`);
// Retrieve all window actors
let windowActors = global.get_window_actors();
// Flag to check if Spotify window is found
let spotifyFound = false;
for (let actor of windowActors) {
let window = actor.get_meta_window();
let wmClass = window.get_wm_class();
// Log details for debugging
logDebug(`Window WM_CLASS: ${JSON.stringify(wmClass)} (Type: ${typeof wmClass})`);
logDebug(`Window Title: ${window.get_title()} (Type: ${typeof window.get_title()})`);
logDebug(`Window Workspace: ${window.get_workspace()} (Type: ${typeof window.get_workspace()})`);
let isSpotify = false;
if (Array.isArray(wmClass)) {
// If wmClass is an array, check if any element matches 'spotify'
isSpotify = wmClass.some(cls => cls.toLowerCase() === 'spotify');
} else if (typeof wmClass === 'string') {
// If wmClass is a string, check if it matches 'spotify'
isSpotify = wmClass.toLowerCase() === 'spotify';
}
if (isSpotify) {
// Validate that 'window' has the 'activate' method
if (typeof window.activate !== 'function') {
logDebug('Window does not have an activate method. Skipping.');
continue;
}
try {
if (window.minimized) {
// If the window is minimized, unminimize and activate
window.unminimize();
logDebug("Spotify window unminimized");
window.activate(global.get_current_time());
logDebug("Spotify window activated");
} else {
// If it's not minimized and the user wants to
// minimize on second click, do so. Otherwise, do nothing.
if (minimizeOnSecondClick) {
window.minimize();
logDebug("Spotify window minimized");
} else {
logDebug("Spotify already in foreground; doing nothing.");
}
}
spotifyFound = true;
break; // Exit once we handle the Spotify window
} catch (e) {
logError(e, 'Failed to activate Spotify window');
}
}
}
if (!spotifyFound) {
logDebug('Spotify window not found. Attempting to launch Spotify to show its window.');
this._launchSpotifyProcess(() => {});
}
}
/**
* Monitors Spotify's presence on the D-Bus.
* Shows or hides the indicator based on whether Spotify is running.
*/
_monitorSpotifyPresence() {
logDebug('Starting to monitor Spotify presence');
this.hide();
// Watch for the Spotify MPRIS D-Bus name to appear or vanish
this._spotifyWatcherId = Gio.DBus.session.watch_name(
SPOTIFY_BUS_NAME,
Gio.BusNameWatcherFlags.NONE,
this._onSpotifyAppeared.bind(this),
this._onSpotifyVanished.bind(this)
);
}
/**
* Callback function when Spotify appears on the D-Bus.
* Shows the indicator and subscribes to property changes.
*/
async _onSpotifyAppeared() {
logDebug('Spotify appeared on D-Bus');
this.show();
// Subscribe to the PropertiesChanged signal first
this._signalSubscriptionId = Gio.DBus.session.signal_subscribe(
SPOTIFY_BUS_NAME,
PROPERTIES_INTERFACE,
'PropertiesChanged',
SPOTIFY_OBJECT_PATH,
null,
Gio.DBusSignalFlags.NONE,
this._onPropertiesChanged.bind(this)
);
// Fetch the initial PlaybackStatus and Metadata from Spotify after subscribing
try {
let playbackStatus = await this._getPlaybackStatus();
this._updatePlayPauseIcon(playbackStatus);
await this._retryFetchMetadata();
} catch (e) {
logError(e, 'Failed to get initial PlaybackStatus or Metadata');
}
}
/**
* Retry fetching Metadata with specified retries and delay.
* @param {number} retries - Number of retry attempts.
* @param {number} delay - Delay between retries in milliseconds.
*/
async _retryFetchMetadata(retries = 3, delay = 500) {
for (let i = 0; i < retries; i++) {
try {
let metadata = await this._getMetadata();
if (metadata['xesam:artist'] && metadata['xesam:title']) {
this._updateTrackInfo(metadata);
logDebug('Successfully fetched valid Metadata on retry');
return;
}
} catch (e) {
logError(e, 'Retry fetching Metadata failed');
}
// Await the cancellable sleep
await this._sleep(delay);
}
logDebug('Failed to fetch valid Metadata after retries');
}
/**
* Sleeps for the specified delay in milliseconds.
* The timeout is tracked and can be cleared upon destruction.
* @param {number} delay - The delay in milliseconds.
* @returns {Promise<void>} - A Promise that resolves after the delay.
*/
_sleep(delay) {
return new Promise((resolve) => {
const timeoutID = setTimeout(() => {
resolve();
// Remove the timeoutID from activeTimeouts once resolved
const index = this._activeTimeouts.indexOf(timeoutID);
if (index > -1) {
this._activeTimeouts.splice(index, 1);
}
}, delay);
this._activeTimeouts.push(timeoutID);
});
}
/**
* Handler for the PropertiesChanged signal from Spotify.
* Updates the UI elements based on the changed properties.
* @param {Gio.DBusConnection} connection - The D-Bus connection.
* @param {string} sender - The sender's bus name.
* @param {string} objectPath - The object path of the signal.
* @param {string} interfaceName - The interface name of the signal.
* @param {string} signalName - The name of the signal.
* @param {GLib.Variant} parameters - The parameters of the signal.
*/
_onPropertiesChanged(connection, sender, objectPath, interfaceName, signalName, parameters) {
let [iface, changedProps, invalidatedProps] = parameters.deep_unpack();
// Check if the signal is from the MPRIS Player Interface
if (iface === MPRIS_PLAYER_INTERFACE) {
// If PlaybackStatus has changed, update the Play/Pause button icon
if (changedProps.PlaybackStatus) {
let playbackStatus = changedProps.PlaybackStatus.deep_unpack();
this._updatePlayPauseIcon(playbackStatus);
logDebug(`PlaybackStatus changed to ${playbackStatus}`);
}
// If Metadata has changed, update the track information label
if (changedProps.Metadata) {
let metadataVariant = changedProps.Metadata.deep_unpack();
// Convert the metadata Variant into a plain JavaScript object
let metadata = {};
for (let key in metadataVariant) {
metadata[key] = metadataVariant[key].deep_unpack();
}
logDebug(`PropertiesChanged Metadata: ${JSON.stringify(metadata)}`);
this._updateTrackInfo(metadata);
}
}
}
/**
* Retrieves the current PlaybackStatus from Spotify using D-Bus.
* @returns {Promise<string>} - A promise that resolves to the playback status.
*/
async _getPlaybackStatus() {
return new Promise((resolve, reject) => {
Gio.DBus.session.call(
SPOTIFY_BUS_NAME,
SPOTIFY_OBJECT_PATH,
PROPERTIES_INTERFACE,
'Get',
new GLib.Variant('(ss)', [MPRIS_PLAYER_INTERFACE, 'PlaybackStatus']), // Parameters for the method
GLib.VariantType.new('(v)'), // Expected return type
Gio.DBusCallFlags.NONE,
-1,
null,
(connection, result) => {
try {
let response = connection.call_finish(result);
let [playbackStatusVariant] = response.deep_unpack();
let playbackStatus = playbackStatusVariant.deep_unpack();
logDebug(`Fetched PlaybackStatus: ${playbackStatus}`);
resolve(playbackStatus);
} catch (e) {
logError(e, 'Failed to fetch PlaybackStatus');
reject(e);
}
}
);
});
}
/**
* Retrieves the current Metadata from Spotify using D-Bus.
* @returns {Promise<Object>} - A promise that resolves to the metadata object.
*/
async _getMetadata() {
return new Promise((resolve, reject) => {
Gio.DBus.session.call(
SPOTIFY_BUS_NAME,
SPOTIFY_OBJECT_PATH,
PROPERTIES_INTERFACE,
'Get',
new GLib.Variant('(ss)', [MPRIS_PLAYER_INTERFACE, 'Metadata']),
GLib.VariantType.new('(v)'),
Gio.DBusCallFlags.NONE,
-1,
null,
(connection, result) => {
try {
let response = connection.call_finish(result);
let [metadataVariant] = response.deep_unpack();
let metadata = metadataVariant.deep_unpack();
let metadataUnpacked = {};
for (let key in metadata) {
metadataUnpacked[key] = metadata[key].deep_unpack();
}
logDebug(`Fetched Metadata: ${JSON.stringify(metadataUnpacked)}`);
resolve(metadataUnpacked);
} catch (e) {
logError(e, 'Failed to fetch Metadata');
reject(e);
}
}
);
});
}
/**
* Updates the track information label with the current artist and song title.
* @param {Object} metadata - The metadata object containing track information.
*/
_updateTrackInfo(metadata) {
let artistArray = this._recursiveUnpack(metadata['xesam:artist']);
let title = this._recursiveUnpack(metadata['xesam:title']);
let artist = _('Unknown Artist');
if (Array.isArray(artistArray) && artistArray.length > 0 && artistArray[0].trim() !== '') {
artist = artistArray[0];
} else {
// Possibly a podcast
// Podcasts have a trackid of /com/spotify/episode and seem to put the
// podcast name in the album property
let trackid = this._recursiveUnpack(metadata['mpris:trackid']);
if (trackid && trackid.startsWith('/com/spotify/episode')) {
let album = this._recursiveUnpack(metadata['xesam:album']);
if (album && album.trim() !== '') {
artist = album;
}
}
}
if (title && title.trim() !== '') {
// Valid title
} else {
title = _('Unknown Title');
}
this.trackLabel.text = `${artist} - ${title}`;
logDebug(`Updated track info: ${artist} - ${title}`);
}
/**
* Recursively unpacks a GLib.Variant if necessary.
* @param {any} variant - The value to unpack.
* @returns {any} - The unpacked value.
*/
_recursiveUnpack(variant) {
if (variant instanceof GLib.Variant) {
return variant.deep_unpack(); // Unpack the Variant to get the raw value
} else {
return variant; // Return the value as-is if it's not a Variant
}
}
/**
* Updates the Play/Pause button icon based on the current playback status.
* @param {string} playbackStatus - The current playback status ('Playing' or other).
*/
_updatePlayPauseIcon(playbackStatus) {
let iconName = (playbackStatus === 'Playing')
? 'media-playback-pause-symbolic'
: 'media-playback-start-symbolic';
if (this.playPauseButton) {
this.playPauseButton.child.icon_name = iconName;
}
logDebug(`Updated play/pause icon to ${iconName}`);
}
/**
* Sends an MPRIS command (e.g., 'Previous', 'PlayPause', 'Next') to Spotify.
* @param {string} command - The MPRIS command to send.
* @returns {Promise<void>} - A promise that resolves when the command is sent successfully.
*/
_sendMPRISCommand(command) {
logDebug(`Sending MPRIS command: ${command}`);
return new Promise((resolve, reject) => {
Gio.DBus.session.call(
SPOTIFY_BUS_NAME,
SPOTIFY_OBJECT_PATH,
MPRIS_PLAYER_INTERFACE,
command,
null,
null,
Gio.DBusCallFlags.NONE,
-1,
null,
(conn, res) => {
try {
conn.call_finish(res);
logDebug(`MPRIS command '${command}' sent successfully`);
resolve();
} catch (e) {
logError(e, `Failed to send MPRIS command: ${command}`);
reject(e);
}
}
);
});
}
/**
* Adjusts the volume based on the scroll direction.
* @param {Clutter.Event} event - The scroll event.
*/
_adjustVolume(actor, event) {
logDebug(`Scroll event detected for volume control`);
let direction = event.get_scroll_direction();
if (direction === Clutter.ScrollDirection.UP) {
this._sendMPRISVolumeCommand('Raise');
} else if (direction === Clutter.ScrollDirection.DOWN) {
this._sendMPRISVolumeCommand('Lower');
}
}
/**
* Sends an MPRIS volume command (e.g., 'Raise', 'Lower') to Spotify.
* @param {string} command - The MPRIS volume command to send.
*/
_sendMPRISVolumeCommand(command) {
logDebug(`Sending MPRIS volume command: ${command}`);
// First, get the current volume
Gio.DBus.session.call(
SPOTIFY_BUS_NAME,
SPOTIFY_OBJECT_PATH,
PROPERTIES_INTERFACE,
'Get',
new GLib.Variant('(ss)', [MPRIS_PLAYER_INTERFACE, 'Volume']),
GLib.VariantType.new('(v)'),
Gio.DBusCallFlags.NONE,
-1,
null,
(conn, res) => {
try {
let response = conn.call_finish(res);
let [volumeVariant] = response.deep_unpack();
let currentVolume = volumeVariant.deep_unpack();
logDebug(`Current volume: ${currentVolume}`);
// Adjust the volume based on the command
let newVolume = currentVolume;
if (command === 'Raise') {
newVolume = Math.min(currentVolume + 0.1, 1.0); // Increase volume by 10%
} else if (command === 'Lower') {
newVolume = Math.max(currentVolume - 0.1, 0.0); // Decrease volume by 10%
}
// Set the new volume
Gio.DBus.session.call(
SPOTIFY_BUS_NAME,
SPOTIFY_OBJECT_PATH,
PROPERTIES_INTERFACE,
'Set',
new GLib.Variant('(ssv)', [MPRIS_PLAYER_INTERFACE, 'Volume', new GLib.Variant('d', newVolume)]),
null,
Gio.DBusCallFlags.NONE,
-1,
null,
(conn, res) => {
try {
conn.call_finish(res);
logDebug(`Volume set to ${newVolume}`);
} catch (e) {
logError(e, `Failed to set volume to ${newVolume}`);
}
}
);
} catch (e) {
logError(e, 'Failed to get current volume');
}
}
);
}
/**
* Callback function when Spotify vanishes from D-Bus.
* Hides the indicator and cleans up signal subscriptions.
*/
_onSpotifyVanished() {
logDebug('Spotify vanished from D-Bus');
this.hide();
if (this._signalSubscriptionId) {
Gio.DBus.session.signal_unsubscribe(this._signalSubscriptionId);
this._signalSubscriptionId = null;
}
}
/**
* Cleans up resources when the SpotifyIndicator is destroyed.
*/
destroy() {
logDebug('Destroying SpotifyIndicator');
// Unwatch Spotify's D-Bus name if it was being watched
if (this._spotifyWatcherId) {
Gio.DBus.session.unwatch_name(this._spotifyWatcherId);
this._spotifyWatcherId = null;
}
// Unsubscribe from the PropertiesChanged signal if subscribed
if (this._signalSubscriptionId) {
Gio.DBus.session.signal_unsubscribe(this._signalSubscriptionId);
this._signalSubscriptionId = null;
}
// Disconnect the 'show-spotify-icon' and 'show-track-info' setting change signals
if (this._showIconChangedId) {
this._settings.disconnect(this._showIconChangedId);
this._showIconChangedId = null;
}
if (this._showTrackInfoChangedId) {
this._settings.disconnect(this._showTrackInfoChangedId);
this._showTrackInfoChangedId = null;
}
if (this._maxWidthChangedId) {
this._settings.disconnect(this._maxWidthChangedId);
this._maxWidthChangedId = null;
}
// Disconnect button-press-event signals before their actors are
// destroyed below.
if (this._buttonSignals) {
for (const { button, signalId } of this._buttonSignals) {
try {
if (button && signalId)
button.disconnect(signalId);
} catch (_) {
// Actor may already be gone; safe to ignore.
}
}
this._buttonSignals = [];
}
// Clear all active timeouts
for (let timeoutID of this._activeTimeouts) {
clearTimeout(timeoutID);
}
this._activeTimeouts = [];
// Optionally, hide or destroy the Spotify icon and track label
if (this.spotifyIcon) {
this.spotifyIcon.destroy();
this.spotifyIcon = null;
}
if (this.trackLabel) {
this.trackLabel.destroy();
this.trackLabel = null;
}
if(this.trackBox){
this.trackBox.destroy();
this.trackBox = null;
}
if (this.trackButton) {
this.trackButton.destroy();
this.trackButton = null;
}
super.destroy();
}
/**
* Try to launch Spotify using the native command first, then fall back
* to `flatpak run com.spotify.Client` on failure.
* @param {Function} [callback] - Optional callback invoked once the
* subprocess has been awaited (only when a callback is passed).
*/
_launchSpotifyProcess(callback) {
let lastError = null;
const tryLaunch = (args) => {
try {
const subprocess = Gio.Subprocess.new(args, Gio.SubprocessFlags.NONE);
if (callback) {
subprocess.wait_async(null, (proc, res) => {
try {
proc.wait_finish(res);
logDebug('Spotify launched successfully to show its window.');
callback();
} catch (e) {
logError(e, 'Failed to launch Spotify to show its window.');
}
});
}
return true;
} catch (e) {
lastError = e;
return false;
}
};
if (tryLaunch(['spotify'])) {
if (!callback)
logDebug('Spotify launched successfully');
return;
}
logDebug('Native spotify not found, trying Flatpak');
if (tryLaunch(['flatpak', 'run', 'com.spotify.Client'])) {
if (!callback)
logDebug('Spotify launched successfully');
return;
}
logError(lastError, 'Error while attempting to launch Spotify subprocess.');
if (callback)
callback();
}
_launchSpotify() {
logDebug('Attempting to launch Spotify');
this._launchSpotifyProcess();
}
}
);
let spotifyIndicator = null;
/**
* SpotifyControlsExtension Class
* Manages the lifecycle (enable/disable) of the Spotify Controls extension.
* Extends the base Extension class to utilize its properties and methods.
*/
export default class SpotifyControlsExtension extends Extension {
/**
* Constructor for SpotifyControlsExtension.
* @param {Object} metadata - The metadata object provided by GNOME Shell.
*/
constructor(metadata) {
super(metadata);
logDebug('Initializing SpotifyControlsExtension');
}
/**
* Called when the extension is enabled.
* Initializes the SpotifyIndicator and adds it to the panel.
*/
enable() {
logDebug('Enabling SpotifyControlsExtension');
this._settings = this.getSettings();
// Connect to changes in various settings
this._positionChangedId = this._settings.connect('changed::position', this._onSettingsChanged.bind(this));
this._controlsPositionChangedId = this._settings.connect('changed::controls-position', this._onSettingsChanged.bind(this));
this._showControlsChangedId = this._settings.connect('changed::show-playback-controls', this._onSettingsChanged.bind(this));
this._volumeControlChangedId = this._settings.connect('changed::enable-volume-control', this._onSettingsChanged.bind(this));
this._showSpotifyIconChangedId = this._settings.connect('changed::show-spotify-icon', this._onSettingsChanged.bind(this));
this._showTrackInfoChangedId = this._settings.connect('changed::show-track-info', this._onSettingsChanged.bind(this));
this._maxWidthChangedId = this._settings.connect('changed::max-width', this._onSettingsChanged.bind(this));
// (No need to connect a signal for minimize-on-second-click unless you
// want to dynamically refresh the behavior mid-session. Typically not necessary.)
this._updateIndicator();
}
/**
* Updates the position of the SpotifyIndicator based on user settings.
*/
_updateIndicator() {
if (spotifyIndicator) {
spotifyIndicator.destroy();
spotifyIndicator = null;
}
// Retrieve settings for indicator position and controls position
let position = this._settings.get_string('position');
let controlsPosition = this._settings.get_string('controls-position');
// Validate 'position' setting
const validPositions = [
'far-left',
'mid-left',
'rightmost-left',
'middle-left',
'center',
'middle-right',
'leftmost-right',
'mid-right',
'far-right',
];
if (!validPositions.includes(position)) {
position = 'rightmost-left'; // Default to 'rightmost-left' if invalid
}