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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
use std::collections::HashMap;
use std::ops::Range;
use std::rc::Rc;
use std::time::Duration;
use dbus::ffidisp::{ConnPath, Connection};
use dbus::strings::{BusName, Path};
use super::{DBusError, LoopStatus, MetadataValue, PlaybackStatus, TrackID, TrackList};
use crate::event::PlayerEvents;
use crate::extensions::DurationExtensions;
use crate::generated::OrgMprisMediaPlayer2;
use crate::generated::OrgMprisMediaPlayer2Player;
use crate::metadata::Metadata;
use crate::pooled_connection::{MprisEvent, PooledConnection};
use crate::progress::ProgressTracker;
pub(crate) const MPRIS2_PREFIX: &str = "org.mpris.MediaPlayer2.";
pub(crate) const MPRIS2_PATH: &str = "/org/mpris/MediaPlayer2";
/// When D-Bus connection is managed for you, use this timeout while communicating with a Player.
pub(crate) const DEFAULT_TIMEOUT_MS: i32 = 500; // ms
/// A MPRIS-compatible player.
///
/// You can query this player about the currently playing media, or control it.
///
/// **See:** [MPRIS2 MediaPlayer2.Player Specification][spec].
///
/// [spec]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html
#[derive(Debug)]
pub struct Player {
connection: Rc<PooledConnection>,
bus_name: String,
unique_name: String,
identity: String,
timeout_ms: i32,
has_tracklist_interface: bool,
}
impl Player {
/// Create a new [`Player`] using a D-Bus connection and address information.
///
/// If no player is running on this bus name an [`Err`] will be returned.
pub fn new(
connection: Connection,
bus_name: String,
timeout_ms: i32,
) -> Result<Player, DBusError> {
Player::for_pooled_connection(Rc::new(connection.into()), bus_name, timeout_ms)
}
pub(crate) fn for_pooled_connection(
pooled_connection: Rc<PooledConnection>,
bus_name: String,
timeout_ms: i32,
) -> Result<Player, DBusError> {
let path: Path = MPRIS2_PATH.into();
let bus: BusName = bus_name.as_str().into();
let identity = {
let connection_path =
pooled_connection.with_path(bus.clone(), path.clone(), timeout_ms);
connection_path.identity()?
};
let unique_name = pooled_connection
.determine_unique_name(&bus_name)
.ok_or_else(|| {
DBusError::Miscellaneous(String::from(
"Could not determine player's unique name. Did it exit during initialization?",
))
})?;
let has_tracklist_interface = {
let connection_path = pooled_connection.with_path(bus, path, timeout_ms);
has_tracklist_interface(connection_path).unwrap_or(false)
};
Ok(Player {
connection: pooled_connection,
bus_name,
unique_name,
identity,
timeout_ms,
has_tracklist_interface,
})
}
/// Returns the current D-Bus communication timeout (in milliseconds).
///
/// When querying D-Bus the call should not block longer than this, and will instead fail the
/// query if no response has been received in this time.
///
/// You can change this using [`set_dbus_timeout_ms`](Self::set_dbus_timeout_ms).
pub fn dbus_timeout_ms(&self) -> i32 {
self.timeout_ms
}
/// Change the D-Bus communication timeout.
pub fn set_dbus_timeout_ms(&mut self, timeout_ms: i32) {
self.timeout_ms = timeout_ms;
}
/// Returns the player's D-Bus bus name.
pub fn bus_name(&self) -> &str {
&self.bus_name
}
/// Returns the player name part of the player's D-Bus bus name.
/// This is the part after "org.mpris.MediaPlayer2.", not including the instance part.
///
/// See: [MPRIS2 specification about bus names][bus_names].
///
/// **Deprecation information:** The MPRIS2 specification doesn't specify how the unique instance
/// identifier part of the bus name should look, therefore every player can ignore the example
/// and implement it in its own way. This method was trying to guess the instance part and was
/// not always successful. See [this issue][issue] for the relevant discussion.
/// In the case when [`identity`][Self::identity] is not able to differentiate the players so
/// you need to filter out players by their bus names you should filter the results of [`PlayerFinder`][crate::find::PlayerFinder].
/// For example:
/// ```no_run
/// use mpris::PlayerFinder;
/// let finder = PlayerFinder::new().unwrap();
/// for player in finder
/// .iter_players()
/// .unwrap()
/// .map(|p| p.unwrap())
/// .filter(|p| p.bus_name_trimmed().starts_with("mpv"))
/// {
/// // Do something with only mpv instances
/// }
///```
///
/// [bus_names]: https://specifications.freedesktop.org/mpris-spec/latest/#Bus-Name-Policy
/// [issue]: https://github.com/Mange/mpris-rs/issues/81
#[deprecated(
since = "2.1.0",
note = "See documentation for explanation, use `bus_name_trimmed` instead"
)]
pub fn bus_name_player_name_part(&self) -> &str {
self.bus_name()
.trim_start_matches(MPRIS2_PREFIX)
.split('.') // Remove the "instance" part
.next()
.unwrap()
}
/// Returns the player name part of the player's D-Bus bus name with the MPRIS2 prefix trimmed.
///
/// Examples:
/// - `org.mpris.MediaPlayer2.io.github.celluloid_player.Celluloid` -> `io.github.celluloid_player.Celluloid`
/// - `org.mpris.MediaPlayer2.Spotify.` -> `Spotify`
/// - `org.mpris.MediaPlayer2.mpv.instance123` -> `mpv.instance123`
pub fn bus_name_trimmed(&self) -> &str {
self.bus_name().trim_start_matches(MPRIS2_PREFIX)
}
/// Returns the player's unique D-Bus bus name (usually something like `:1.1337`).
pub fn unique_name(&self) -> &str {
&self.unique_name
}
/// Returns the player's MPRIS [`Identity`][identity].
///
/// This is usually the application's name, like `Spotify`.
///
/// [identity]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:Identity
pub fn identity(&self) -> &str {
&self.identity
}
/// Checks if the Player implements the `org.mpris.MediaPlayer2.TrackList` interface.
pub fn supports_track_lists(&self) -> bool {
self.has_tracklist_interface
}
/// Returns the player's `DesktopEntry` property, if supported.
///
/// See: [MPRIS2 specification about `DesktopEntry`][desktop_entry].
///
/// [desktop_entry]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:DesktopEntry
pub fn get_desktop_entry(&self) -> Result<Option<String>, DBusError> {
handle_optional_property(self.connection_path().desktop_entry())
}
/// Returns the player's `SupportedMimeTypes` property.
///
/// See: [MPRIS2 specification about `SupportedMimeTypes`][mime_types].
///
/// [mime_types]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:SupportedMimeTypes
pub fn get_supported_mime_types(&self) -> Result<Vec<String>, DBusError> {
self.connection_path()
.supported_mime_types()
.map_err(|e| e.into())
}
/// Returns the player's `SupportedUriSchemes` property.
///
/// See: [MPRIS2 specification about `SupportedUriSchemes`][schemes].
///
/// [schemes]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:SupportedUriSchemes
pub fn get_supported_uri_schemes(&self) -> Result<Vec<String>, DBusError> {
self.connection_path()
.supported_uri_schemes()
.map_err(|e| e.into())
}
/// Returns the player's `HasTrackList` property.
///
/// See: [MPRIS2 specification about `HasTrackList`][track_list].
///
/// [track_list]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:HasTrackList
pub fn get_has_track_list(&self) -> Result<bool, DBusError> {
self.connection_path()
.has_track_list()
.map_err(|e| e.into())
}
/// Returns the player's MPRIS `position` as a [`Duration`] since the start of the media.
pub fn get_position(&self) -> Result<Duration, DBusError> {
self.get_position_in_microseconds()
.map(Duration::from_micros_ext)
}
/// Gets the "Position" setting, if the player indicates that it supports it.
///
/// Return [`Some`] containing the current value of the position. If the setting is not
/// supported, return [`None`]
pub fn checked_get_position(&self) -> Result<Option<Duration>, DBusError> {
if self.has_position()? {
Ok(Some(self.get_position()?))
} else {
Ok(None)
}
}
/// Returns the player's MPRIS `position` as a count of microseconds since the start of the
/// media.
pub fn get_position_in_microseconds(&self) -> Result<u64, DBusError> {
self.connection_path()
.position()
.map(|p| p as u64)
.map_err(|e| e.into())
}
/// Sets the position of the current track to the given position (as a [`Duration`]).
///
/// Current [`TrackID`] must be provided to avoid race conditions with the player, in case it
/// changes tracks while the signal is being sent.
///
/// **Note:** There is currently no good way to retrieve the current [`TrackID`] through the
/// `mpris` library. You will have to manually retrieve it through D-Bus until implemented.
///
/// See: [MPRIS2 specification about `SetPosition`][set_position].
///
/// [set_position]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:SetPosition
pub fn set_position(&self, track_id: TrackID, position: &Duration) -> Result<(), DBusError> {
self.set_position_in_microseconds(track_id, DurationExtensions::as_micros(position))
}
/// Set the "Position" setting of the player, if the player indicates that it supports the
/// "Position" setting and can be controlled.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Position`][position].
///
/// [position]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Position
pub fn checked_set_position(
&self,
track_id: TrackID,
position: &Duration,
) -> Result<bool, DBusError> {
if self.can_control()? && self.has_position()? {
self.set_position(track_id, position).map(|_| true)
} else {
Ok(false)
}
}
/// Sets the position of the current track to the given position (in microseconds).
///
/// Current [`TrackID`] must be provided to avoid race conditions with the player, in case it
/// changes tracks while the signal is being sent.
///
/// **Note:** There is currently no good way to retrieve the current [`TrackID`] through the
/// `mpris` library. You will have to manually retrieve it through D-Bus until implemented.
///
/// See: [MPRIS2 specification about `SetPosition`][set_position].
///
/// [set_position]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:SetPosition
pub fn set_position_in_microseconds(
&self,
track_id: TrackID,
position_in_us: u64,
) -> Result<(), DBusError> {
self.connection_path()
.set_position(track_id.as_path(), position_in_us as i64)
.map_err(|e| e.into())
}
/// Returns the player's MPRIS (playback) `rate` as a factor.
///
/// 1.0 would mean normal rate, while 2.0 would mean twice the playback speed.
pub fn get_playback_rate(&self) -> Result<f64, DBusError> {
self.connection_path().rate().map_err(|e| e.into())
}
/// Gets the "Rate" setting, if the player indicates that it supports it.
///
/// Returns [`Some`] containing the current value of the rate setting. If the setting is not
/// supported, returns [`None`]
pub fn checked_get_playback_rate(&self) -> Result<Option<f64>, DBusError> {
if self.has_playback_rate()? {
Ok(Some(self.get_playback_rate()?))
} else {
Ok(None)
}
}
/// Sets the player's MPRIS (playback) `rate` as a factor.
///
/// 1.0 would mean normal rate, while 2.0 would mean twice the playback speed.
///
/// It is not allowed to try to set playback rate to a value outside of the supported range.
/// [`get_valid_playback_rate_range`](Self::get_valid_playback_rate_range) returns a [`Range<f64>`] that encodes the maximum and
/// minimum values.
///
/// You must not set rate to 0.0; instead call [`pause`](Self::pause).
///
/// See: [MPRIS2 specification about `Rate`][rate].
///
/// [rate]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Rate
pub fn set_playback_rate(&self, rate: f64) -> Result<(), DBusError> {
self.connection_path().set_rate(rate).map_err(|e| e.into())
}
/// Set the playback rate of the player, if the player indicates that supports it and that it
/// can be controlled.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Rate`][rate].
///
/// [rate]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Rate
pub fn checked_set_playback_rate(&self, rate: f64) -> Result<bool, DBusError> {
if self.can_control()? && self.has_playback_rate()? {
self.set_playback_rate(rate).map(|_| true)
} else {
Ok(false)
}
}
/// Gets the minimum allowed value for playback rate.
///
/// See: [MPRIS2 specification about `MinimumRate`][min_rate].
///
/// [min_rate]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:MinimumRate
pub fn get_minimum_playback_rate(&self) -> Result<f64, DBusError> {
self.connection_path().minimum_rate().map_err(|e| e.into())
}
/// Gets the maximum allowed value for playback rate.
///
/// See: [MPRIS2 specification about `MaximumRate`][max_rate].
///
/// [max_rate]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:MaximumRate
pub fn get_maximum_playback_rate(&self) -> Result<f64, DBusError> {
self.connection_path().maximum_rate().map_err(|e| e.into())
}
/// Gets the minimum-maximum allowed value range for playback rate.
///
/// See: [`get_minimum_playback_rate`](Self::get_minimum_playback_rate)
/// and [`get_maximum_playback_rate`](Self::get_maximum_playback_rate).
pub fn get_valid_playback_rate_range(&self) -> Result<Range<f64>, DBusError> {
self.get_minimum_playback_rate()
.and_then(|min| self.get_maximum_playback_rate().map(|max| min..max))
}
/// Query the player for current metadata.
///
/// See [`Metadata`] for more information about what is included here.
pub fn get_metadata(&self) -> Result<Metadata, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
let connection_path = self.connection_path();
Properties::get::<HashMap<String, MetadataValue>>(
&connection_path,
"org.mpris.MediaPlayer2.Player",
"Metadata",
)
.map(Metadata::from)
.map_err(DBusError::from)
}
/// Query the player for the current tracklist.
///
/// **Note:** It's more expensive to rebuild this each time rather than trying to keep the same
/// [`TrackList`] updated. See [`TrackList::reload`].
///
/// See [`checked_get_track_list`](Self::checked_get_track_list) to automatically detect players not supporting track lists.
pub fn get_track_list(&self) -> Result<TrackList, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
let connection_path = self.connection_path();
Properties::get::<Vec<Path<'_>>>(
&connection_path,
"org.mpris.MediaPlayer2.TrackList",
"Tracks",
)
.map(TrackList::from)
.map_err(DBusError::from)
}
/// Query the player for the current tracklist.
///
/// **Note:** It's more expensive to rebuild this each time rather than trying to keep the same
/// [`TrackList`] updated. See [`TrackList::reload`].
///
/// See [`get_track_list`](Self::get_track_list), [`supports_track_lists`](Self::supports_track_lists) and
/// [`get_has_track_list`](Self::get_has_track_list) if you want to manually handle compatibility checks.
pub fn checked_get_track_list(&self) -> Result<Option<TrackList>, DBusError> {
if self.supports_track_lists() && self.get_has_track_list()? {
self.get_track_list().map(Some)
} else {
Ok(None)
}
}
/// Query the player to see if it allows changes to its TrackList.
///
/// Will return [`Err`] if Player isn't supporting the [`TrackList`] interface.
///
/// See [`checked_can_edit_tracks`](Self::checked_can_edit_tracks) to automatically detect players not supporting track lists.
///
/// See: [MPRIS2 specification about `CanEditTracks`][can_edit].
///
/// [can_edit]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Property:CanEditTracks
pub fn can_edit_tracks(&self) -> Result<bool, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
let connection_path = self.connection_path();
Properties::get::<bool>(
&connection_path,
"org.mpris.MediaPlayer2.TrackList",
"CanEditTracks",
)
.map_err(DBusError::from)
}
/// Query the player to see if it allows changes to its TrackList.
///
/// Will return [`false`] if [`Player`] isn't supporting the `TrackList` interface.
///
/// See [`can_edit_tracks`](Self::can_edit_tracks) and [`supports_track_lists`](Self::supports_track_lists)
/// if you want to manually handle compatibility checks.
///
/// See: [MPRIS2 specification about `CanEditTracks`][can_edit].
///
/// [can_edit]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Property:CanEditTracks
pub fn checked_can_edit_tracks(&self) -> bool {
if self.supports_track_lists() {
self.can_edit_tracks().unwrap_or(false)
} else {
false
}
}
/// Query the player for metadata for the given [`TrackID`]s.
///
/// This is used by the [`TrackList`] type to iterator metadata for the tracks in the track list.
///
/// See: [MediaPlayer2.TrackList.GetTracksMetadata][get_meta].
///
/// [get_meta]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Method:GetTracksMetadata
pub fn get_tracks_metadata(&self, track_ids: &[TrackID]) -> Result<Vec<Metadata>, DBusError> {
use dbus::arg::IterAppend;
let connection_path = self.connection_path();
let mut method = connection_path.method_call_with_args(
&"org.mpris.MediaPlayer2.TrackList".into(),
&"GetTracksMetadata".into(),
|msg| {
let mut i = IterAppend::new(msg);
i.append(track_ids.iter().map(|id| id.as_path()).collect::<Vec<_>>());
},
)?;
method.as_result()?;
let mut i = method.iter_init();
let metadata: Vec<::std::collections::HashMap<String, MetadataValue>> = i.read()?;
if metadata.len() == track_ids.len() {
Ok(metadata.into_iter().map(Metadata::from).collect())
} else {
Err(DBusError::Miscellaneous(format!(
"Expected {} tracks, but got {} tracks returned.",
track_ids.len(),
metadata.len()
)))
}
}
/// Query the player for metadata for a single [`TrackID`].
///
/// Note that [`get_tracks_metadata`](Self::get_tracks_metadata) with a list is more effective if you have more than a
/// single [`TrackID`] to load.
///
/// See: [MediaPlayer2.TrackList.GetTracksMetadata][get_meta].
///
/// [get_meta]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Method:GetTracksMetadata
pub fn get_track_metadata(&self, track_id: &TrackID) -> Result<Metadata, DBusError> {
self.get_tracks_metadata(std::slice::from_ref(track_id))
.and_then(|mut result| {
result.pop().map(Ok).unwrap_or_else(|| {
Err(DBusError::Miscellaneous(format!(
"Player gave no Metadata for {}",
track_id
)))
})
})
}
/// Returns a new [`ProgressTracker`] for the player.
///
/// Use this if you want to monitor a player in order to show close-to-realtime information
/// about it.
///
/// It is built like a blocking "frame limiter" where it returns at an approximately fixed
/// interval with the most up-to-date information. It's mostly appropriate when trying to
/// render something like a progress bar, or information about the current track.
///
/// See: [`events`](Self::events) for an alternative approach.
pub fn track_progress(&self, interval_ms: u32) -> Result<ProgressTracker<'_>, DBusError> {
ProgressTracker::new(self, interval_ms)
}
/// Returns a [`PlayerEvents`] iterator, or an [`DBusError`] if there was a problem with the D-Bus
/// connection to the player.
///
/// This iterator will block until an event for the current player is emitted. This is a lot
/// more bare-bones than [`track_progress`](Self::track_progress), but it's also something that makes it easier
/// for you to translate events into your own application's domain events and only deal with
/// actual changes.
///
/// You could implement your own progress tracker on top of this, but it's probably not
/// appropriate to render a live progress bar using this iterator as the progress bar will
/// remain frozen until the next event is emitted and the iterator returns.
///
/// See: [`track_progress`](Self::track_progress) for an alternative approach.
pub fn events(&self) -> Result<PlayerEvents<'_>, DBusError> {
PlayerEvents::new(self)
}
/// Returns true if the bus of this player is still occupied in the connection, or put in
/// another way: If there's a process still listening on messages on this bus.
///
/// If the player that you are controlling / querying has shut down, then this would return
/// false. You can use this to do graceful restarts, begin looking for another player, etc.
pub fn is_running(&self) -> bool {
self.connection()
.name_has_owner(self.bus_name.to_string())
.unwrap_or(false)
}
pub(crate) fn connection(&self) -> &PooledConnection {
&self.connection
}
/// Send a `PlayPause` signal to the player.
///
/// See: [MPRIS2 specification about `PlayPause`][play_pause]
///
/// [play_pause]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:PlayPause
pub fn play_pause(&self) -> Result<(), DBusError> {
self.connection_path().play_pause().map_err(|e| e.into())
}
/// Send a `Play` signal to the player.
///
/// See: [MPRIS2 specification about `Play`][play].
///
/// [play]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Play
pub fn play(&self) -> Result<(), DBusError> {
self.connection_path().play().map_err(|e| e.into())
}
/// Send a `Pause` signal to the player.
///
/// See: [MPRIS2 specification about `Pause`][pause].
///
/// [pause]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Pause
pub fn pause(&self) -> Result<(), DBusError> {
self.connection_path().pause().map_err(|e| e.into())
}
/// Send a `Stop` signal to the player.
///
/// See: [MPRIS2 specification about `Stop`][stop].
///
/// [stop]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Stop
pub fn stop(&self) -> Result<(), DBusError> {
self.connection_path().stop().map_err(|e| e.into())
}
/// Send a `Next` signal to the player.
///
/// See: [MPRIS2 specification about `Next`][next].
///
/// [next]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Next
pub fn next(&self) -> Result<(), DBusError> {
self.connection_path().next().map_err(|e| e.into())
}
/// Send a `Previous` signal to the player.
///
/// See: [MPRIS2 specification about `Previous`][prev].
///
/// [prev]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Previous
pub fn previous(&self) -> Result<(), DBusError> {
self.connection_path().previous().map_err(|e| e.into())
}
/// Send a `Seek` signal to the player.
///
/// See: [MPRIS2 specification about `Seek`][seek].
///
/// [seek]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Seek
pub fn seek(&self, offset_in_microseconds: i64) -> Result<(), DBusError> {
self.connection_path()
.seek(offset_in_microseconds)
.map_err(|e| e.into())
}
/// Tell the player to seek forwards.
///
/// See: [`seek`](Self::seek) method.
pub fn seek_forwards(&self, offset: &Duration) -> Result<(), DBusError> {
self.seek(DurationExtensions::as_micros(offset) as i64)
}
/// Send a `Raise` signal to the player.
///
/// > Brings the media player's user interface to the front using any appropriate mechanism
/// > available.
/// >
/// > The media player may be unable to control how its user interface is displayed, or it may
/// > not have a graphical user interface at all. In this case, the CanRaise property is false
/// > and this method does nothing.
///
/// See: [MPRIS2 specification about `Raise`][raise] and the [`can_raise`](Self::can_raise) method.
///
/// [raise]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Method:Raise
pub fn raise(&self) -> Result<(), DBusError> {
self.connection_path().raise().map_err(|e| e.into())
}
/// Send a `Raise` signal to the player, if it supports it.
///
/// See: [`can_raise`](Self::can_raise) and [`raise`](Self::raise) methods.
pub fn checked_raise(&self) -> Result<bool, DBusError> {
if self.can_raise()? {
self.raise().map(|_| true)
} else {
Ok(false)
}
}
/// Send a `Quit` signal to the player.
///
/// > Causes the media player to stop running.
/// >
/// > The media player may refuse to allow clients to shut it down. In this case, the CanQuit
/// > property is false and this method does nothing.
/// >
/// > Note: Media players which can be D-Bus activated, or for which there is no sensibly easy
/// > way to terminate a running instance (via the main interface or a notification area icon for
/// > example) should allow clients to use this method. Otherwise, it should not be needed.
/// >
/// > If the media player does not have a UI, this should be implemented.
///
/// See: [MPRIS2 specification about `Quit`][quit] and the [`can_quit`](Self::can_quit) method.
///
/// [quit]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Method:Quit
pub fn quit(&self) -> Result<(), DBusError> {
self.connection_path().quit().map_err(|e| e.into())
}
/// Send a `Quit` signal to the player, if it supports it.
///
/// See: [`can_quit`](Self::can_quit) and [`quit`](Self::quit) methods.
pub fn checked_quit(&self) -> Result<bool, DBusError> {
if self.can_quit()? {
self.quit().map(|_| true)
} else {
Ok(false)
}
}
/// Tell the player to seek backwards.
///
/// See: [`seek`](Self::seek) method.
pub fn seek_backwards(&self, offset: &Duration) -> Result<(), DBusError> {
self.seek(-(DurationExtensions::as_micros(offset) as i64))
}
/// Go to a specific track on the [`Player`]'s [`TrackList`].
///
/// If the given [`TrackID`] is not part of the player's [`TrackList`], it will have no effect.
///
/// Requires the player to implement the `TrackList` interface.
///
/// See: [MPRIS2 specification about `GoTo`][go_to]
///
/// [go_to]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Method:GoTo
pub fn go_to(&self, track_id: &TrackID) -> Result<(), DBusError> {
use crate::generated::OrgMprisMediaPlayer2TrackList;
self.connection_path()
.go_to(track_id.into())
.map_err(DBusError::from)
}
/// Add a URI to the TrackList and optionally set it as current.
///
/// It is placed after the specified [`TrackID`], if supported by the player.
///
/// Requires the player to implement the `TrackList` interface.
///
/// See: [MPRIS2 specification about `AddTrack`][add_track].
///
/// [add_track]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Method:AddTrack
pub fn add_track(
&self,
uri: &str,
after: &TrackID,
set_as_current: bool,
) -> Result<(), DBusError> {
use crate::generated::OrgMprisMediaPlayer2TrackList;
self.connection_path()
.add_track(uri, after.into(), set_as_current)
.map_err(DBusError::from)
}
/// Add a URI to the start of the TrackList and optionally set it as current.
///
/// Requires the player to implement the `TrackList` interface.
///
/// See: [MPRIS2 specification about `AddTrack`][add_track].
///
/// [add_track]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Method:AddTrack
pub fn add_track_at_start(&self, uri: &str, set_as_current: bool) -> Result<(), DBusError> {
use crate::generated::OrgMprisMediaPlayer2TrackList;
self.connection_path()
.add_track(uri, crate::track_list::NO_TRACK.into(), set_as_current)
.map_err(DBusError::from)
}
/// Remove an item from the TrackList.
///
/// Requires the player to implement the `TrackList` interface.
///
/// See: [MPRIS2 specification about `RemoveTrack`][remove].
///
/// [remove]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html#Method:RemoveTrack
pub fn remove_track(&self, track_id: &TrackID) -> Result<(), DBusError> {
use crate::generated::OrgMprisMediaPlayer2TrackList;
self.connection_path()
.remove_track(track_id.into())
.map_err(DBusError::from)
}
/// Sends a `PlayPause` signal to the player, if the player indicates that it can pause.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `PlayPause`][play_pause]
///
/// [play_pause]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:PlayPause
pub fn checked_play_pause(&self) -> Result<bool, DBusError> {
if self.can_pause()? {
self.play_pause().map(|_| true)
} else {
Ok(false)
}
}
/// Sends a `Play` signal to the player, if the player indicates that it can play.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Play`][play].
///
/// [play]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Play
pub fn checked_play(&self) -> Result<bool, DBusError> {
if self.can_play()? {
self.play().map(|_| true)
} else {
Ok(false)
}
}
/// Sends a `Pause` signal to the player, if the player indicates that it can pause.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Pause`][pause].
///
/// [pause]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Pause
pub fn checked_pause(&self) -> Result<bool, DBusError> {
if self.can_pause()? {
self.pause().map(|_| true)
} else {
Ok(false)
}
}
/// Sends a `Stop` signal to the player, if the player indicates that it can stop.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Stop`][stop].
///
/// [stop]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Stop
pub fn checked_stop(&self) -> Result<bool, DBusError> {
if self.can_stop()? {
self.stop().map(|_| true)
} else {
Ok(false)
}
}
/// Sends a `Next` signal to the player, if the player indicates that it can go to the next
/// media.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Next`][next].
///
/// [next]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Next
pub fn checked_next(&self) -> Result<bool, DBusError> {
if self.can_go_next()? {
self.next().map(|_| true)
} else {
Ok(false)
}
}
/// Sends a `Previous` signal to the player, if the player indicates that it can go to a
/// previous media.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Previous`][prev].
///
/// [prev]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Previous
pub fn checked_previous(&self) -> Result<bool, DBusError> {
if self.can_go_previous()? {
self.previous().map(|_| true)
} else {
Ok(false)
}
}
/// Sends a `Seek` signal to the player, if the player indicates that it can seek.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Seek`][seek].
///
/// [seek]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Seek
pub fn checked_seek(&self, offset_in_microseconds: i64) -> Result<bool, DBusError> {
if self.can_seek()? {
self.seek(offset_in_microseconds).map(|_| true)
} else {
Ok(false)
}
}
/// Seeks the player forwards, if the player indicates that it can seek.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Seek`][seek].
///
/// [seek]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Seek
pub fn checked_seek_forwards(&self, offset: &Duration) -> Result<bool, DBusError> {
if self.can_seek()? {
self.seek_forwards(offset).map(|_| true)
} else {
Ok(false)
}
}
/// Seeks the player backwards, if the player indicates that it can seek.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Seek`][seek].
///
/// [seek]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Seek
pub fn checked_seek_backwards(&self, offset: &Duration) -> Result<bool, DBusError> {
if self.can_seek()? {
self.seek_backwards(offset).map(|_| true)
} else {
Ok(false)
}
}
/// Queries the player to see if it can be raised or not.
///
/// See: [MPRIS2 specification about `CanRaise`][can_raise] and the [`raise`](Self::raise) method.
///
/// [can_raise]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanRaise
pub fn can_raise(&self) -> Result<bool, DBusError> {
self.connection_path().can_raise().map_err(|e| e.into())
}
/// Queries the player to see if it can be asked to quit.
///
/// See: [MPRIS2 specification about `CanQuit`][can_quit] and the [`quit`](Self::quit) method.
///
/// [can_quit]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanQuit
pub fn can_quit(&self) -> Result<bool, DBusError> {
self.connection_path().can_quit().map_err(|e| e.into())
}
/// Queries the player to see if it can be asked to entrer fullscreen.
///
/// This property was added in MPRIS 2.2, and not all players will implement it. This method
/// will try to detect this case and fall back to `Ok(false)`.
///
/// It is up to you to decide if you want to ignore errors caused by this method or not.
///
/// See: [MPRIS2 specification about `CanSetFullscreen`][can_full] and the [`set_fullscreen`](Self::set_fullscreen) method.
///
/// [can_full]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:CanSetFullscreen
pub fn can_set_fullscreen(&self) -> Result<bool, DBusError> {
handle_optional_property(self.connection_path().can_set_fullscreen())
.map(|o| o.unwrap_or(false))
}
/// Queries the player to see if it can be controlled or not.
///
/// See: [MPRIS2 specification about `CanControl`][can_control].
///
/// [can_control]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanControl
pub fn can_control(&self) -> Result<bool, DBusError> {
self.connection_path().can_control().map_err(|e| e.into())
}
/// Queries the player to see if it can go to next or not.
///
/// See: [MPRIS2 specification about `CanGoNext`][can_next].
///
/// [can_next]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanGoNext
pub fn can_go_next(&self) -> Result<bool, DBusError> {
self.connection_path().can_go_next().map_err(|e| e.into())
}
/// Queries the player to see if it can go to previous or not.
///
/// See: [MPRIS2 specification about `CanGoPrevious`][can_prev].
///
/// [can_prev]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanGoPrevious
pub fn can_go_previous(&self) -> Result<bool, DBusError> {
self.connection_path()
.can_go_previous()
.map_err(|e| e.into())
}
/// Queries the player to see if it can pause.
///
/// See: [MPRIS2 specification about `CanPause`][can_pause]
///
/// [can_pause]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanPause
pub fn can_pause(&self) -> Result<bool, DBusError> {
self.connection_path().can_pause().map_err(|e| e.into())
}
/// Queries the player to see if it can play.
///
/// See: [MPRIS2 specification about `CanPlay`][can_play].
///
/// [can_play]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanPlay
pub fn can_play(&self) -> Result<bool, DBusError> {
self.connection_path().can_play().map_err(|e| e.into())
}
/// Queries the player to see if it can seek within the media.
///
/// See: [MPRIS2 specification about `CanSeek`][can_seek].
///
/// [can_seek]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanSeek
pub fn can_seek(&self) -> Result<bool, DBusError> {
self.connection_path().can_seek().map_err(|e| e.into())
}
/// Queries the player to see if it can stop.
///
/// MPRIS2 defines [the `Stop` message to only work when the player can be controlled][can_stop], so that
/// is the property used for this method.
///
/// See: [MPRIS2 specification about `CanControl`][can_control].
///
/// [can_stop]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Method:Stop
/// [can_control]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:CanControl
pub fn can_stop(&self) -> Result<bool, DBusError> {
self.can_control()
}
/// Queries the player to see if it currently supports/allows changing playback rate.
pub fn can_set_playback_rate(&self) -> Result<bool, DBusError> {
self.get_valid_playback_rate_range()
.map(|range| range.start < 1.0 || range.end > 1.0)
}
/// Queries the player to see if it supports the "Shuffle" setting
pub fn can_shuffle(&self) -> Result<bool, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
self.connection_path()
.get_all("org.mpris.MediaPlayer2.Player")
.map(|props| props.contains_key("Shuffle"))
.map_err(DBusError::from)
}
/// Queries the player to see if it supports the "LoopStatus" setting
pub fn can_loop(&self) -> Result<bool, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
self.connection_path()
.get_all("org.mpris.MediaPlayer2.Player")
.map(|props| props.contains_key("LoopStatus"))
.map_err(DBusError::from)
}
/// Queries the player to see if it supports the "Rate" setting
pub fn has_playback_rate(&self) -> Result<bool, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
self.connection_path()
.get_all("org.mpris.MediaPlayer2.Player")
.map(|props| props.contains_key("Rate"))
.map_err(DBusError::from)
}
/// Queries the player to see if it supports the "Position" setting
pub fn has_position(&self) -> Result<bool, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
self.connection_path()
.get_all("org.mpris.MediaPlayer2.Player")
.map(|props| props.contains_key("Position"))
.map_err(DBusError::from)
}
/// Queries the player to see if it supports the "Volume" setting
pub fn has_volume(&self) -> Result<bool, DBusError> {
use dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties;
self.connection_path()
.get_all("org.mpris.MediaPlayer2.Player")
.map(|props| props.contains_key("Volume"))
.map_err(DBusError::from)
}
/// Query the player for current fullscreen state.
///
/// This property was added in MPRIS 2.2, and not all players will implement it. This method
/// will try to detect this case and fall back to `Ok(None)`.
///
/// It is up to you to decide if you want to ignore errors caused by this method or not.
///
/// See: [MPRIS2 specification about `Fullscreen`][full] and the [`can_set_fullscreen`](Self::can_set_fullscreen) method.
///
/// [full]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:Fullscreen
pub fn get_fullscreen(&self) -> Result<Option<bool>, DBusError> {
handle_optional_property(self.connection_path().fullscreen())
}
/// Asks the player to change fullscreen state.
///
/// If method call succeeded, `Ok(true)` will be returned.
///
/// This property was added in MPRIS 2.2, and not all players will implement it. This method
/// will try to detect this case and fall back to `Ok(false)`.
///
/// Other errors will be returned as [`Err`].
///
/// See: [MPRIS2 specification about `Fullscreen`][full] and the [`can_set_fullscreen`](Self::can_set_fullscreen) method.
///
/// [full]: https://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html#Property:Fullscreen
pub fn set_fullscreen(&self, new_state: bool) -> Result<bool, DBusError> {
handle_optional_property(self.connection_path().set_fullscreen(new_state))
.map(|o| o.is_some())
}
/// Query the player for current playback status.
pub fn get_playback_status(&self) -> Result<PlaybackStatus, DBusError> {
self.connection_path()
.playback_status()?
.parse()
.map_err(DBusError::from)
}
/// Query player for the state of the "Shuffle" setting.
///
/// See: [MPRIS2 specification about `Shuffle`][shuffle].
///
/// [shuffle]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Shuffle
pub fn get_shuffle(&self) -> Result<bool, DBusError> {
self.connection_path().shuffle().map_err(DBusError::from)
}
/// Gets the "Shuffle" setting, if the player indicates that it supports it.
///
/// Return [`Some`] containing the current value of the shuffle setting. If the setting is not
/// supported, will return [`None`]
pub fn checked_get_shuffle(&self) -> Result<Option<bool>, DBusError> {
if self.can_shuffle()? {
Ok(Some(self.get_shuffle()?))
} else {
Ok(None)
}
}
/// Set the "Shuffle" setting of the player.
///
/// See: [MPRIS2 specification about `Shuffle`][shuffle].
///
/// [shuffle]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Shuffle
pub fn set_shuffle(&self, state: bool) -> Result<(), DBusError> {
self.connection_path()
.set_shuffle(state)
.map_err(DBusError::from)
}
/// Set the "Shuffle" setting of the player, if the player indicates that it supports the
/// "Shuffle" setting and can be controlled.
///
/// Returns a [`bool`] to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Shuffle`][shuffle].
///
/// [shuffle]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Shuffle
pub fn checked_set_shuffle(&self, state: bool) -> Result<bool, DBusError> {
if self.can_control()? && self.can_shuffle()? {
self.set_shuffle(state).map(|_| true)
} else {
Ok(false)
}
}
/// Query the player for the current loop status.
///
/// See: [MPRIS2 specification about `LoopStatus`][loop_status].
///
/// [loop_status]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:LoopStatus
pub fn get_loop_status(&self) -> Result<LoopStatus, DBusError> {
self.connection_path()
.loop_status()?
.parse()
.map_err(DBusError::from)
}
/// Gets the "LoopStatus" setting, if the player indicates that it supports it.
///
/// Returns [`Some`] containing the current value of the loop setting. If the setting is not
/// supported, returns [`None`]
pub fn checked_get_loop_status(&self) -> Result<Option<LoopStatus>, DBusError> {
if self.can_loop()? {
Ok(Some(self.get_loop_status()?))
} else {
Ok(None)
}
}
/// Set the loop status of the player.
///
/// See: [MPRIS2 specification about `LoopStatus`][loop_status].
///
/// [loop_status]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:LoopStatus
pub fn set_loop_status(&self, status: LoopStatus) -> Result<(), DBusError> {
self.connection_path()
.set_loop_status(status.dbus_value())
.map_err(DBusError::from)
}
/// Set the loop status of the player, if the player indicates that supports it and that it can
/// be controlled.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `LoopStatus`][loop_status].
///
/// [loop_status]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:LoopStatus
pub fn checked_set_loop_status(&self, status: LoopStatus) -> Result<bool, DBusError> {
if self.can_control()? && self.can_loop()? {
self.set_loop_status(status).map(|_| true)
} else {
Ok(false)
}
}
/// Get the volume of the player.
///
/// Volume should be between 0.0 and 1.0. Above 1.0 is possible, but not
/// recommended.
///
/// See: [MPRIS2 specification about `Volume`][vol].
///
/// [vol]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Volume
pub fn get_volume(&self) -> Result<f64, DBusError> {
self.connection_path().volume().map_err(DBusError::from)
}
/// Gets the "Volume" setting, if the player indicates that it supports it.
///
/// Returns [`Some`] containing the current value of the position. If the setting is not
/// supported, returns [`None`]
pub fn checked_get_volume(&self) -> Result<Option<f64>, DBusError> {
if self.has_volume()? {
Ok(Some(self.get_volume()?))
} else {
Ok(None)
}
}
/// Set the volume of the player.
///
/// Volume should be between 0.0 and 1.0. Above 1.0 is possible, but not
/// recommended.
///
/// See: [MPRIS2 specification about `Volume`][vol].
///
/// [vol]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Volume
pub fn set_volume(&self, value: f64) -> Result<(), DBusError> {
self.connection_path()
.set_volume(value.max(0.0))
.map_err(DBusError::from)
}
/// Set the "Volume" setting of the player, if the player indicates that it supports the
/// "Volume" setting and can be controlled.
///
/// Returns a boolean to show if the signal was sent or not.
///
/// See: [MPRIS2 specification about `Volume`][vol].
///
/// [vol]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Volume
pub fn checked_set_volume(&self, volume: f64) -> Result<bool, DBusError> {
if self.can_control()? && self.has_volume()? {
self.set_volume(volume).map(|_| true)
} else {
Ok(false)
}
}
/// Set the volume of the player, if the player indicates that it can be
/// controlled.
///
/// Volume should be between 0.0 and 1.0. Above 1.0 is possible, but not
/// recommended.
///
/// See: [MPRIS2 specification about `Volume`][vol].
///
/// [vol]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Property:Volume
pub fn set_volume_checked(&self, value: f64) -> Result<bool, DBusError> {
if self.can_control()? {
self.set_volume(value).map(|_| true)
} else {
Ok(false)
}
}
fn connection_path(&self) -> ConnPath<'_, &Connection> {
self.connection.with_path(
self.bus_name.as_str().into(),
MPRIS2_PATH.into(),
self.timeout_ms,
)
}
/// Blocks until player gets an event on the bus.
///
/// Other player events will also be recorded, but will not cause this function to return. Note
/// that this will block forever if player is not running. Make sure to check that the player
/// is running before calling this method!
pub(crate) fn process_events_blocking_until_received(&self) {
while !self.connection.has_pending_events(&self.unique_name) {
self.connection.process_events_blocking_until_received();
}
}
/// Return any events that are pending (for this player) on the connection.
pub(crate) fn pending_events(&self) -> Vec<MprisEvent> {
self.connection.pending_events(&self.unique_name)
}
}
fn handle_optional_property<T>(result: Result<T, dbus::Error>) -> Result<Option<T>, DBusError> {
if let Err(ref error) = result {
if let Some(error_name) = error.name() {
if error_name == "org.freedesktop.DBus.Error.InvalidArgs" {
// This property was likely just missing, which means that the player has not
// implemented it.
return Ok(None);
}
}
}
result.map(Some).map_err(|e| e.into())
}
/// Checks if the Player implements the `org.mpris.MediaPlayer2.TrackList` interface.
fn has_tracklist_interface(connection: ConnPath<'_, &Connection>) -> Result<bool, DBusError> {
// Get the introspection XML and look for the substring instead of parsing the XML. Yeah,
// pretty dirty, but it's also a lot faster and doesn't require a huge XML library as a
// dependency either.
//
// It's probably accurate enough.
use dbus::ffidisp::stdintf::OrgFreedesktopDBusIntrospectable;
let xml: String = connection.introspect()?;
Ok(xml.contains("org.mpris.MediaPlayer2.TrackList"))
}