/
dbus.js
1972 lines (1814 loc) · 66.2 KB
/
dbus.js
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
/*
* Mpris Indicator Button extension for Gnome Shell 3.34+
* Copyright 2020 Jason Gray (JasonLG1979)
*
* 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
* (at your option) 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 <http://www.gnu.org/licenses/>.
*
* If this extension breaks your desktop you get to keep all of the pieces...
*/
// No translatable strings in this file.
const { Gio, GLib, GObject, Gtk, Meta, Shell } = imports.gi;
const { activateWindow } = imports.ui.main;
const UUID = imports.misc.extensionUtils.getCurrentExtension().metadata.uuid;
const MPRIS_PREFIX = 'org.mpris.MediaPlayer2.';
// See https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Simple-Type:Track_Id
const NO_TRACK_PATH = '/org/mpris/MediaPlayer2/TrackList/NoTrack';
const FORBIDDEN_OBJ_ID_PREFIX = '/org/mpris';
const METADATA_KEYS = [
'xesam:artist',
'xesam:albumArtist',
'xesam:composer',
'xesam:lyricist',
'rhythmbox:streamTitle',
'xesam:title',
'xesam:trackNumber',
'xesam:album',
'xesam:discNumber',
'mpris:artUrl',
'mpris:trackid',
'xesam:url'
];
const Node = Gio.DBusNodeInfo.new_for_xml(
`<node>
<interface name='org.freedesktop.DBus'>
<method name='GetConnectionUnixProcessID'>
<arg type='s' direction='in' />
<arg type='u' direction='out' />
</method>
<method name='ListNames'>
<arg type='as' direction='out' />
</method>
<signal name='NameOwnerChanged'>
<arg type='s' direction='out' />
<arg type='s' direction='out' />
<arg type='s' direction='out' />
</signal>
</interface>
<interface name='org.mpris.MediaPlayer2'>
<method name='Raise' />
<method name='Quit' />
<property name='CanQuit' type='b' access='read' />
<property name='CanRaise' type='b' access='read' />
<property name='Identity' type='s' access='read' />
<property name='DesktopEntry' type='s' access='read' />
</interface>
<interface name='org.mpris.MediaPlayer2.Player'>
<method name='PlayPause' />
<method name='Next' />
<method name='Previous' />
<method name='Stop' />
<method name='Play' />
<property name='CanControl' type='b' access='read' />
<property name='CanGoNext' type='b' access='read' />
<property name='CanGoPrevious' type='b' access='read' />
<property name='CanPlay' type='b' access='read' />
<property name='CanPause' type='b' access='read' />
<property name='Metadata' type='a{sv}' access='read' />
<property name='PlaybackStatus' type='s' access='read' />
<property name='Shuffle' type='b' access='readwrite' />
<property name='LoopStatus' type='s' access='readwrite' />
<property name='Volume' type='d' access='readwrite' />
</interface>
<interface name='org.mpris.MediaPlayer2.TrackList'>
<method name='GetTracksMetadata'>
<arg type='ao' direction='in' />
<arg type='aa{sv}' direction='out' />
</method>
<method name='GoTo'>
<arg type='o' direction='in' />
</method>
<property name='Tracks' type='ao' access='read' />
<signal name='TrackListReplaced'>
<arg type='ao' direction='out' />
<arg type='o' direction='out' />
</signal>
<signal name='TrackAdded'>
<arg type='a{sv}' direction='out' />
<arg type='o' direction='out' />
</signal>
<signal name='TrackRemoved'>
<arg type='o' direction='out' />
</signal>
<signal name='TrackMetadataChanged'>
<arg type='o' direction='out' />
<arg type='a{sv}' direction='out' />
</signal>
</interface>
<interface name='org.mpris.MediaPlayer2.Playlists'>
<method name='ActivatePlaylist'>
<arg type='o' direction='in' />
</method>
<method name='GetPlaylists'>
<arg type='u' direction='in' />
<arg type='u' direction='in' />
<arg type='s' direction='in' />
<arg type='b' direction='in' />
<arg type='a(oss)' direction='out' />
</method>
<property name='PlaylistCount' type='u' access='read' />
<property name='Orderings' type='as' access='read' />
<property name='ActivePlaylist' type='(b(oss))' access='read' />
<signal name='PlaylistChanged'>
<arg type='(oss)' direction='out' />
</signal>
</interface>
</node>`);
function makeProxy(ifaceName, busName, objectPath, flags, asyncCallback) {
let cancellable = null;
let error = null;
let proxy = null;
let iface = Node.interfaces.find(iface => iface.name === ifaceName);
if (iface) {
flags = flags !== null
? Gio.DBusProxyFlags.DO_NOT_AUTO_START | flags
: Gio.DBusProxyFlags.DO_NOT_AUTO_START;
cancellable = new Gio.Cancellable();
Gio.DBusProxy.new(
Gio.DBus.session,
flags,
iface,
busName,
objectPath,
ifaceName,
cancellable,
(source, result) => {
try {
proxy = Gio.DBusProxy.new_finish(result);
} catch(e) {
proxy = null;
error = e;
} finally {
if (proxy) {
if (!proxy.g_name_owner) {
error = Gio.DBusError.new_for_dbus_error(
' No Name Owner',
`${busName} has no owner.`
);
}
} else if (!error) {
// Should never really happen.
error = Gio.DBusError.new_for_dbus_error(
' Unknow Error',
busName
);
}
asyncCallback(proxy, error);
}
}
);
}
return cancellable;
}
function makeDBusProxy(asyncCallback) {
return makeProxy(
'org.freedesktop.DBus',
'org.freedesktop.DBus',
'/org/freedesktop/DBus',
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES,
asyncCallback
);
}
function makeMprisProxy(busName, asyncCallback) {
return makeProxy(
'org.mpris.MediaPlayer2',
busName,
'/org/mpris/MediaPlayer2',
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS | Gio.DBusProxyFlags.GET_INVALIDATED_PROPERTIES,
asyncCallback
);
}
function makePlayerProxy(busName, asyncCallback) {
return makeProxy(
'org.mpris.MediaPlayer2.Player',
busName,
'/org/mpris/MediaPlayer2',
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS | Gio.DBusProxyFlags.GET_INVALIDATED_PROPERTIES,
asyncCallback
);
}
function makeTrackListProxy(busName, asyncCallback) {
return makeProxy(
'org.mpris.MediaPlayer2.TrackList',
busName,
'/org/mpris/MediaPlayer2',
null,
asyncCallback
);
}
function makePlayListProxy(busName, asyncCallback) {
return makeProxy(
'org.mpris.MediaPlayer2.Playlists',
busName,
'/org/mpris/MediaPlayer2',
Gio.DBusProxyFlags.GET_INVALIDATED_PROPERTIES,
asyncCallback
);
}
function makeMprisPoxies(busName, asyncCallback) {
let mpris, player, tracklist, playlist;
let onProxyReady = (proxy, error) => {
if (error && cancellables) {
cancellables.forEach(cancellable => {
if (!cancellable.is_cancelled()) {
cancellable.cancel();
}
cancellable.run_dispose();
});
cancellables = null;
if (proxy) {
proxy.run_dispose();
}
[mpris, player, tracklist, playlist].forEach(proxy => {
if (proxy) {
proxy.run_dispose();
}
});
mpris = player = tracklist = playlist = null;
asyncCallback(error, mpris, player, tracklist, playlist);
} else if (proxy) {
if (proxy.g_interface_name === 'org.mpris.MediaPlayer2') {
mpris = proxy;
}
if (proxy.g_interface_name === 'org.mpris.MediaPlayer2.Player') {
player = proxy;
}
if (proxy.g_interface_name === 'org.mpris.MediaPlayer2.TrackList') {
tracklist = proxy;
}
if (proxy.g_interface_name === 'org.mpris.MediaPlayer2.Playlists') {
playlist = proxy;
}
if (mpris && player && tracklist && playlist) {
cancellables.forEach(cancellable => {
cancellable.run_dispose();
});
cancellables = null;
asyncCallback(null, mpris, player, tracklist, playlist);
}
}
};
let cancellables = [
makeMprisProxy(busName, onProxyReady),
makePlayerProxy(busName, onProxyReady),
makeTrackListProxy(busName, onProxyReady),
makePlayListProxy(busName, onProxyReady)
];
}
function parseMetadata(metadata, playerName) {
metadata = metadata || {};
playerName = playerName || '';
let mimetype_icon = 'audio-x-generic-symbolic';
let obj_id = NO_TRACK_PATH;
let cover_url = '';
let artist = playerName;
let title = '';
if (Object.keys(metadata).length) {
// Unpack all Metadata keys that we care about in place.
// If the key doesn't exsist set it to an empty string and join all arrays.
// Most of our 'artist' keys are (or at least should be) arrays of strings.
METADATA_KEYS.forEach(key => {
let value = metadata[key] ? metadata[key].deep_unpack() : '';
metadata[key] = Array.isArray(value) ? value.join(', ') : value;
});
cover_url = metadata['mpris:artUrl'];
obj_id = metadata['mpris:trackid'] || NO_TRACK_PATH;
let trackUrl = metadata['xesam:url'];
// Spotify videos and ads don't follow MPRIS metadata spec.
// This more or less matches what Spotify shows in it's UI.
if (playerName === 'Spotify' && !trackUrl.includes('/track/')) {
mimetype_icon = (!trackUrl || trackUrl.includes('/episode/')) ? 'video-x-generic-symbolic' : 'audio-x-generic-symbolic';
if (!metadata['xesam:artist']) {
let delimiter = metadata['xesam:title'].includes(' - ') ? ' - ' : ': ';
let artist_title = metadata['xesam:title'].split(delimiter);
if (artist_title.length > 1) {
artist = artist_title.shift().trim() || playerName;
title = artist_title.join(delimiter).trim();
} else {
delimiter = metadata['xesam:album'].includes(' - ') ? ' - ' : ': ';
artist = metadata['xesam:album'].split(delimiter)[0].trim() || playerName;
title = metadata['xesam:title'];
}
} else {
artist = metadata['xesam:artist'];
title = metadata['xesam:title'];
}
} else {
// There are better ways to sniff the mimetype of the track
// but they involve doing I/O on the url which isn't worth it.
// This is good enough and works just fine most of the time.
// If all else fails fallback to 'audio-x-generic-symbolic'
if (trackUrl) {
let fileExt = `.${trackUrl.split(/\#|\?/)[0].split('.').pop().trim()}`;
let [mimetype, uncertain] = Gio.content_type_guess(fileExt, null);
mimetype_icon = (!uncertain && Gio.content_type_is_a(mimetype, 'video/*'))
? 'video-x-generic-symbolic'
: 'audio-x-generic-symbolic';
}
// Be rather exhaustive and liberal as far as what constitutes an 'artist'.
// If all else fails fallback to the Player's name.
artist = metadata['xesam:artist'] ? metadata['xesam:artist']
: metadata['xesam:albumArtist'] ? metadata['xesam:albumArtist']
: metadata['xesam:composer'] ? metadata['xesam:composer']
: metadata['xesam:lyricist'] ? metadata['xesam:lyricist']
: metadata['rhythmbox:streamTitle'] ? metadata['rhythmbox:streamTitle']
: playerName;
// Prefer the track title, but in it's absence if the
// track number and album title are available use them.
// For example, '5 - My favorite Album'.
// If the disc number is more than 1 also add the disc number.
// for example, '5 - My favorite Album (2)'.
// If all else fails fallback to an empty string.
title = metadata['xesam:title'] ? metadata['xesam:title']
: (Number.isInteger(metadata['xesam:trackNumber'])
&& Number.isInteger(metadata['xesam:discNumber'])
&& metadata['xesam:discNumber'] > 1
&& metadata['xesam:album'])
? `${metadata['xesam:trackNumber']} - ${metadata['xesam:album']} (${metadata['xesam:discNumber']})`
: (Number.isInteger(metadata['xesam:trackNumber'])
&& metadata['xesam:album'])
? `${metadata['xesam:trackNumber']} - ${metadata['xesam:album']}`
: '';
}
}
return [obj_id, cover_url, artist, title, mimetype_icon];
}
function logMyError(error) {
// Cancelling counts as an error don't spam the logs.
if (!error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
logError(error, `Extension ${UUID}`);
}
}
var DBusProxyHandler = GObject.registerClass({
GTypeName: 'DBusProxyHandler',
Signals: {
'add-player': {
flags: GObject.SignalFlags.RUN_FIRST,
param_types: [
GObject.TYPE_STRING, // busName
GObject.TYPE_OBJECT, // MprisProxyHandler
GObject.TYPE_OBJECT, // TrackListProxyHandler
GObject.TYPE_OBJECT // PlayListProxyHandler
]
},
'remove-player': {
flags: GObject.SignalFlags.RUN_FIRST,
param_types: [
GObject.TYPE_STRING // busName
]
}
}
}, class DBusProxyHandler extends GObject.Object {
_init() {
super._init();
this._proxy = null;
this._nameOwnerId = null;
this._ignoredPlayers = [];
this._cancellable = makeDBusProxy(this._onProxyReady.bind(this));
}
_onProxyReady(proxy, error) {
this._cancellable.run_dispose();
if (proxy) {
this._proxy = proxy;
this._proxy.ListNamesRemote(([n]) => {
let players = n.filter(n => n.startsWith(MPRIS_PREFIX));
players.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())).forEach(p => this._addPlayer(p));
});
this._nameOwnerId = this._proxy.connectSignal('NameOwnerChanged', (...[,,[busName, oldOwner, newOwner]]) => {
if (busName.startsWith(MPRIS_PREFIX) && !this._ignoredPlayers.includes(this._stripInstanceNumber(busName))) {
if (newOwner) {
this._addPlayer(busName);
} else {
this.emit('remove-player', busName);
}
}
});
} else {
logMyError(error);
}
this._cancellable = null;
}
_stripInstanceNumber(busName) {
return busName.replace(/\d+$/, '');
}
_addPlayer(busName) {
this._proxy.GetConnectionUnixProcessIDRemote(busName, ([pid]) => {
makeMprisPoxies(busName, (error, mpris, player, tracklist, playlist) => {
if (error) {
logMyError(error);
if (this._proxy) {
let badBusName = this._stripInstanceNumber(busName);
if (!this._ignoredPlayers.includes(badBusName)) {
this._ignoredPlayers.push(badBusName);
this.emit('remove-player', busName);
}
}
} else if (this._proxy) {
mpris = new MprisProxyHandler(pid, mpris, player);
tracklist = new TrackListProxyHandler(tracklist);
playlist = new PlayListProxyHandler(playlist);
this.emit('add-player', busName, mpris, tracklist, playlist);
}
});
});
}
destroy() {
if (this._cancellable) {
if (!this._cancellable.is_cancelled()) {
this._cancellable.cancel();
}
this._cancellable.run_dispose();
}
if (this._proxy) {
if (this._nameOwnerId) {
this._proxy.disconnectSignal(this._nameOwnerId);
}
this._proxy.run_dispose();
}
this._proxy = null;
this._nameOwnerId = null;
this._cancellable = null;
this._ignoredPlayers = null;
super.run_dispose();
}
});
// Things get a little weird when there are more
// than one instance of a player running at the same time.
// As far as ShellApp is concerned they are the same app.
// So we have to jump though a bunch of hoops to keep track
// of and differentiate the instance metaWindows by pid or
// gtk_unique_bus_name/nameOwner.
const AppWrapper = GObject.registerClass({
GTypeName: 'AppWrapper',
Properties: {
'focused': GObject.ParamSpec.boolean(
'focused',
'focused-prop',
'If the instance of the app is focused',
GObject.ParamFlags.READABLE,
false
)
}
}, class AppWrapper extends GObject.Object {
_init(shellApp, busName, pid, nameOwner) {
super._init();
this._app = shellApp;
this._pid = pid;
this._appName = this._app.get_name();
this._appId = this._app.id.split('/').pop().replace('.desktop', '');
this._instanceNum = this._getNumbersFromTheEndOf(busName);
this._nameOwner = nameOwner;
this._focused = false;
this._user_time = 0;
this._userActivated = false;
this._metaWindow = null;
this._appearsFocusedId = null;
this._unmanagedId = null;
this._metaWindowsChangedId = this._app.connect(
'windows-changed',
this._onWindowsChanged.bind(this)
);
this._onWindowsChanged();
}
get focused() {
return this._focused || false;
}
get id() {
return this._appId || '';
}
get name() {
return this._appName || '';
}
get user_time() {
return this._user_time || 0;
}
get can_quit() {
return this._metaWindow ? true : false;
}
get gicon() {
// Much prefer a Gio.FileIcon or Gio.ThemedIcon to the St.Icon
// you'd get from Shell.App.create_icon_texture().
// This also doesn't fail silently and return the wrong icon...
let app_info = this._app.get_app_info();
return app_info ? app_info.get_icon() : null;
}
request_quit() {
this._app.request_quit();
}
toggleWindow(minimize) {
if (!this._focused) {
// Go ahead and skip the whole 'Player is Ready'
// notification, after all the user wants the player focused,
// that's why they clicked on it...
if (this._metaWindow) {
activateWindow(this._metaWindow);
return true;
} else {
if (!this._app.is_window_backed() && !this._app.get_busy()) {
this._userActivated = true;
this._app.activate();
return true;
} else {
return false;
}
}
} else if (minimize && this._metaWindow && this._metaWindow.can_minimize()) {
this._metaWindow.minimize();
return true;
}
return false;
}
destroy() {
// Nothing to see here, move along...
if (this._metaWindowsChangedId) {
this._app.disconnect(this._metaWindowsChangedId);
}
this._onUnmanaged();
this._metaWindowsChangedId = null;
this._app = null;
this._pid = null;
this._appId = null;
this._appName = null;
this._focused = null;
this._user_time = null;
this._userActivated = null;
super.run_dispose();
}
_getNumbersFromTheEndOf(someString) {
let matches = someString.match(/[0-9]+$/);
return matches ? parseInt(matches[0], 10) : null;
}
_getNormalAppMetaWindows() {
// We don't want dialogs or what not...
return Array.from(this._app.get_windows()).filter(w =>
!w.skip_taskbar && w.window_type === Meta.WindowType.NORMAL
);
}
_getNewAppMetaWindow() {
// Try to get a hold of an actual metaWindow...
let metaWindows = this._getNormalAppMetaWindows();
let metaWindow = metaWindows.find(w => {
// Check for multiple instances.
if (this._instanceNum && w.gtk_window_object_path) {
// Match multiple instance(multiple window really) GApplications to their windows.
// Works rather well if a GApplication's MPRIS instance number matches
// it's corresponding window object path like the latest git master of GNOME-MPV.
// For example org.mpris.MediaPlayer2.GnomeMpv.instance-1 = /io/github/GnomeMpv/window/1.
let windowNum = this._getNumbersFromTheEndOf(w.gtk_window_object_path);
if (this._instanceNum === windowNum) {
return true;
}
} else if (w.gtk_unique_bus_name) {
// This will match single instance GApplications to their window.
// Generally the window and MPRIS interface will have the
// same name owner.
if (w.gtk_unique_bus_name === this._nameOwner) {
return true;
}
// Match true multiple instances players by their pids.
// works rather well for apps like VLC for example.
} else if (w.get_pid() === this._pid) {
return true;
}
return false;
});
return metaWindow ? metaWindow : metaWindows.length ? metaWindows[0] : null;
}
_grabAppMetaWindow(appMetaWindow) {
// Connect our metaWindow signals
// and check the new window's focus.
if (appMetaWindow) {
this._onUnmanaged();
this._metaWindow = appMetaWindow;
this._appearsFocusedId = this._metaWindow.connect(
'notify::appears-focused',
this._onAppearsFocused.bind(this)
);
this._unmanagedId = this._metaWindow.connect(
'unmanaged',
this._onUnmanaged.bind(this)
);
this._onAppearsFocused();
if (!this._focused && this._userActivated) {
activateWindow(this._metaWindow);
}
}
}
_onWindowsChanged() {
// We get this signal when metaWindows show up
// Really only useful when a player 'unhides'
// or at _init
let appMetaWindow = this._getNewAppMetaWindow();
if (appMetaWindow) {
while (appMetaWindow.get_transient_for()) {
appMetaWindow = appMetaWindow.get_transient_for();
}
}
if (this._metaWindow !== appMetaWindow) {
this._grabAppMetaWindow(appMetaWindow);
}
this._userActivated = false;
}
_onAppearsFocused() {
// Pretty self explanatory...
let focused = this._metaWindow && this._metaWindow.has_focus();
if (this._focused != focused) {
this._user_time = GLib.get_monotonic_time();
this._focused = focused;
this.notify('focused');
}
}
_onUnmanaged() {
// 'unmanaged' metaWindows are either hidden and/or
// will soon be destroyed. Disconnect from them
// and null the metaWindow.
if (this._metaWindow) {
if (this._appearsFocusedId) {
this._metaWindow.disconnect(this._appearsFocusedId);
}
if (this._unmanagedId) {
this._metaWindow.disconnect(this._unmanagedId);
}
}
this._metaWindow = null;
this._appearsFocusedId = null;
this._unmanagedId = null;
}
});
const TrackListProxyHandler = GObject.registerClass({
GTypeName: 'TrackListProxyHandler',
Signals: {
'new-metadata': {
flags: GObject.SignalFlags.RUN_FIRST
},
'metadata-changed': {
flags: GObject.SignalFlags.RUN_FIRST,
param_types: [
GObject.TYPE_STRING, // old_obj_id
GObject.TYPE_STRING, // obj_id
GObject.TYPE_STRING, // cover_url
GObject.TYPE_STRING, // artist
GObject.TYPE_STRING, // title
GObject.TYPE_STRING // mimetype_icon
]
}
},
Properties: {
'player-name': GObject.ParamSpec.string(
'player-name',
'player-name-prop',
'The player\'s name',
GObject.ParamFlags.READWRITE,
''
),
'current-obj-id': GObject.ParamSpec.string(
'current-obj-id',
'current-obj-id-prop',
'The current track\'s trackId',
GObject.ParamFlags.READWRITE,
''
),
'list-title': GObject.ParamSpec.string(
'list-title',
'list-title-prop',
'The title of the corresponding list',
GObject.ParamFlags.READABLE,
'TrackList'
),
'show-list': GObject.ParamSpec.boolean(
'show-list',
'show-list-prop',
'If the track list should be shown',
GObject.ParamFlags.READABLE,
false
)
}
}, class TrackListProxyHandler extends GObject.Object {
_init(proxy) {
super._init();
this._proxy = proxy;
this._signals = [];
this._current_obj_id = '';
this._ifaceName = this._proxy.g_interface_name.split('.').pop();
this._show_list = false;
this._list_title = this._ifaceName;
this._trackIds = [];
this._metadata = [];
this._player_name = '';
this._finish_init();
}
get ifaceName() {
return this._ifaceName || '';
}
get busName() {
return this._proxy ? this._proxy.g_name : '';
}
get show_list() {
return this._show_list || false;
}
get list_title() {
return this._list_title || '';
}
get player_name() {
return this._player_name || '';
}
set player_name(player_name) {
this._player_name = player_name;
this.notify('player-name');
}
get current_obj_id() {
return this._current_obj_id || '';
}
set current_obj_id(current_obj_id) {
this._current_obj_id = current_obj_id;
this.notify('current-obj-id');
}
get metadata() {
return this._metadata ? this._metadata : [];
}
goTo(trackId) {
if (this._proxy && this._trackListIncludes(trackId)) {
this._proxy.GoToRemote(trackId);
}
}
refresh() {
if (this._proxy && Array.isArray(this._trackIds) && this._trackIds.length) {
this._replaceTracklist(this._trackIds);
}
}
_syncTrackListProps() {
let show_list = Array.isArray(this._trackIds) && this._trackIds.length ? true : false;
if (this._show_list !== show_list) {
this._show_list = show_list;
this.notify('show-list');
}
if (this._show_list) {
this.notify('current-obj-id');
}
}
_getTrackId(metadata) {
metadata = metadata || {};
return metadata['mpris:trackid'] ? (metadata['mpris:trackid'].deep_unpack() || NO_TRACK_PATH) : NO_TRACK_PATH;
}
_trackListIncludes(trackId) {
return Array.isArray(this._trackIds) && this._goodTrackListId(trackId) && this._trackIds.includes(trackId);
}
_goodTrackListId(trackId) {
return trackId && !trackId.startsWith(FORBIDDEN_OBJ_ID_PREFIX);
}
_cleanTrackIds(trackIds) {
trackIds = trackIds && Array.isArray(trackIds) ? trackIds : [];
return trackIds.filter((id, i, a) => this._goodTrackListId(id) && a.indexOf(id) === i);
}
_cleanMetadata(metadata) {
metadata = metadata && Array.isArray(metadata) ? metadata : [];
return metadata.map(m => parseMetadata(m, this._player_name)).filter((m, i, a) => {
return this._goodTrackListId(m[0]) && a.findIndex(m2 => m2[0] === m[0]) === i;
});
}
_arraysOfEqualLenght(...arrays) {
return new Set(arrays.map(array => array.length)).size === 1;
}
_replaceTracklist(trackIds) {
trackIds = this._cleanTrackIds(trackIds);
this._trackIds = [];
this._metadata = [];
if (trackIds.length) {
this._proxy.GetTracksMetadataRemote(trackIds, ([trackListMetaData]) => {
let cleanMetadata = this._cleanMetadata(trackListMetaData);
if (this._arraysOfEqualLenght(trackIds, trackListMetaData, cleanMetadata)) {
this._trackIds = cleanMetadata.map(m => m[0]);
this._metadata = cleanMetadata;
this.emit('new-metadata');
}
this._syncTrackListProps();
});
} else {
this._syncTrackListProps();
}
}
_finish_init() {
this._trackIds = this._cleanTrackIds(this._proxy.Tracks);
this.pushSignal('TrackListReplaced', (...[,,[trackIds]]) => {
this._replaceTracklist(trackIds);
});
this.pushSignal('TrackAdded', (...[,,[metadata, afterTrackId]]) => {
let newTrackId = this._getTrackId(metadata);
if (this._goodTrackListId(newTrackId) && !this._trackListIncludes(newTrackId)) {
if (afterTrackId) {
if (afterTrackId === NO_TRACK_PATH) {
this._trackIds.unshift(newTrackId);
} else if (this._trackListIncludes(afterTrackId)) {
this._trackIds.splice(this._trackIds.indexOf(afterTrackId) + 1, 0, newTrackId);
}
this._replaceTracklist(this._trackIds);
}
}
});
this.pushSignal('TrackRemoved', (...[,,[trackId]]) => {
if (this._trackListIncludes(trackId)) {
this._trackIds.splice(this._trackIds.indexOf(trackId), 1);
this._replaceTracklist(this._trackIds);
}
});
this.pushSignal('TrackMetadataChanged', (...[,,[oldtrackId, metadata]]) => {
if (this._trackListIncludes(oldtrackId)) {
let [newTrackId, cover_url, artist, title, mimetype_icon] = parseMetadata(metadata, this._player_name);
if (this._goodTrackListId(newTrackId)) {
let index = this._trackIds.indexOf(oldtrackId);
this._metadata[index] = [newTrackId, cover_url, artist, title, mimetype_icon];
this._trackIds[index] = newTrackId;
this.emit(
'metadata-changed',
oldtrackId,
newTrackId,
cover_url,
artist,
title,
mimetype_icon
);
this._syncTrackListProps();
}
}
});
}
pushSignal(signalName, callback) {
this._signals.push(this._proxy.connectSignal(signalName, callback));
}
destroy() {
if (this._proxy) {
this._signals.forEach(id => this._proxy.disconnectSignal(id));
this._proxy.run_dispose();
}
this._signals = null;
this._proxy = null;
this._current_obj_id = null;
this._ifaceName = null;
this._show_list = null;
this._list_title = null;
this._trackIds = null;
this._metadata = null;
this._player_name = null;
super.run_dispose();
}
});
const PlayListProxyHandler = GObject.registerClass({
GTypeName: 'PlayListProxyHandler',
Signals: {
'new-metadata': {
flags: GObject.SignalFlags.RUN_FIRST
},
'metadata-changed': {
flags: GObject.SignalFlags.RUN_FIRST,
param_types: [
GObject.TYPE_STRING, // obj_id
GObject.TYPE_STRING, // obj_id
GObject.TYPE_STRING // title
]
}
},
Properties: {
'player-name': GObject.ParamSpec.string(
'player-name',
'player-name-prop',
'The player\'s name',
GObject.ParamFlags.READWRITE,
''
),
'current-obj-id': GObject.ParamSpec.string(
'current-obj-id',
'current-obj-id-prop',
'The current playlist\'s playlistId',
GObject.ParamFlags.READABLE,
''
),
'list-title': GObject.ParamSpec.string(
'list-title',
'list-title-prop',
'The title of the corresponding list',
GObject.ParamFlags.READABLE,
'PlayLists'
),
'show-list': GObject.ParamSpec.boolean(
'show-list',
'show-list-prop',
'If the PlayLists should be shown',
GObject.ParamFlags.READABLE,
false
)
}
}, class PlayListProxyHandler extends GObject.Object {
_init(proxy) {
super._init();
this._proxy = proxy;
this._playlists = [];
this._player_name = '';
this._current_obj_id = '';
this._ifaceName = this._proxy.g_interface_name.split('.').pop();
this._show_list = false;
this._list_title = this._ifaceName;
this._propChangeId = null;
this._getPlayListsId = null;
this._finish_init();
}
get ifaceName() {
return this._ifaceName || '';
}
get busName() {
return this._proxy ? this._proxy.g_name : '';