mpris 2.1.0

Idiomatic MPRIS D-Bus interface library
Documentation
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
use super::{DBusError, Metadata, Player};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::iter::{FromIterator, IntoIterator};
use thiserror::Error;

pub(crate) const NO_TRACK: &str = "/org/mpris/MediaPlayer2/TrackList/NoTrack";

/// Represents [the MPRIS `Track_Id` type][track_id].
///
/// ```rust
/// use mpris::TrackID;
/// let no_track = TrackID::new("/org/mpris/MediaPlayer2/TrackList/NoTrack").unwrap();
/// ```
///
/// TrackIDs must be valid D-Bus object paths according to the spec.
///
/// # Errors
///
/// Trying to construct a [`TrackID`] from a string that is not a valid D-Bus Path will fail.
///
/// ```rust
/// # use mpris::TrackID;
/// let result = TrackID::new("invalid track ID");
/// assert!(result.is_err());
/// ```
///
/// [track_id]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Simple-Type:Track_Id
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct TrackID(pub(crate) String);

/// Represents a [`MediaPlayer2.TrackList`][track_list].
///
/// This type offers an iterator of the track's metadata, when provided a [`Player`] instance that
/// matches the list.
///
/// TrackLists cache metadata about tracks so multiple iterations should be fast. It also enables
/// signals received from the Player to pre-populate metadata and to keep everything up to date.
///
/// [track_list]: https://specifications.freedesktop.org/mpris-spec/latest/Track_List_Interface.html
#[derive(Debug, Default)]
pub struct TrackList {
    ids: Vec<TrackID>,
    metadata_cache: RefCell<HashMap<TrackID, Metadata>>,
}

/// TrackList-related errors.
///
/// This is mostly [`DBusError`] with the extra possibility of borrow errors of the internal metadata
/// cache.
#[derive(Debug, Error)]
pub enum TrackListError {
    /// Something went wrong with the D-Bus communication. See the [`DBusError`] type.
    #[error("D-Bus communication failed: {0}")]
    DBusError(#[from] DBusError),

    /// Something went wrong with the borrowing logic for the internal cache. Perhaps you have
    /// multiple borrowed references to the cache live at the same time, for example because of
    /// multiple iterations?
    #[error("Could not borrow cache: {0}")]
    BorrowError(String),
}

#[derive(Debug)]
pub struct MetadataIter {
    order: Vec<TrackID>,
    metadata: HashMap<TrackID, Metadata>,
    current: usize,
}

impl<'a> From<dbus::Path<'a>> for TrackID {
    fn from(path: dbus::Path<'a>) -> TrackID {
        TrackID(path.to_string())
    }
}

impl<'a> From<&'a TrackID> for TrackID {
    fn from(id: &'a TrackID) -> Self {
        TrackID(id.0.clone())
    }
}

impl From<TrackID> for String {
    fn from(id: TrackID) -> String {
        id.0
    }
}

impl<'a> From<&'a TrackID> for dbus::Path<'a> {
    fn from(id: &'a TrackID) -> dbus::Path<'a> {
        id.as_path()
    }
}

impl fmt::Display for TrackID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl TrackID {
    /// Create a new [`TrackID`] from a string-like entity.
    ///
    /// This is not something you should normally do as the IDs are temporary and will only work if
    /// the Player knows about it.
    ///
    /// However, creating [`TrackID`]s manually can help with test setup, comparisons, etc.
    ///
    /// # Example
    /// ```rust
    /// use mpris::TrackID;
    /// let id = TrackID::new("/dbus/path/id").expect("Parse error");
    /// ```
    pub fn new<S: Into<String>>(id: S) -> Result<Self, String> {
        let id = id.into();
        // Validate the ID by constructing a dbus::Path.
        if let Err(error) = dbus::Path::new(id.as_str()) {
            Err(error)
        } else {
            Ok(TrackID(id))
        }
    }

    /// Return a new [`TrackID`] that matches the MPRIS standard for the "No track" sentinel value.
    ///
    /// Some APIs takes this in order to signal a missing value for a track, for example by saying
    /// that no specific track is playing, or that a track should be added at the start of the
    /// list instead of after a specific track.
    ///
    /// The actual path is "/org/mpris/MediaPlayer2/TrackList/NoTrack".
    ///
    /// This value is only valid in some cases. Make sure to read the [MPRIS specification before
    /// you use this manually][track_id].
    ///
    /// [track_id]: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html#Simple-Type:Track_Id
    pub fn no_track() -> Self {
        TrackID(NO_TRACK.into())
    }

    /// Returns a `&str` variant of the ID.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub(crate) fn as_path(&self) -> dbus::Path<'_> {
        // All inputs to this class should be validated to work with [`dbus::Path`], so unwrapping
        // should be safe here.
        dbus::Path::new(self.as_str()).unwrap()
    }
}

impl AsRef<str> for TrackID {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl From<Vec<TrackID>> for TrackList {
    fn from(ids: Vec<TrackID>) -> Self {
        TrackList::new(ids)
    }
}

impl<'a> From<Vec<dbus::Path<'a>>> for TrackList {
    fn from(ids: Vec<dbus::Path<'a>>) -> Self {
        ids.into_iter().map(TrackID::from).collect()
    }
}

impl FromIterator<TrackID> for TrackList {
    fn from_iter<I: IntoIterator<Item = TrackID>>(iter: I) -> Self {
        TrackList::new(iter.into_iter().collect())
    }
}

impl TrackList {
    /// Construct a new [`TrackList`] without any existing cache.
    pub fn new(ids: Vec<TrackID>) -> TrackList {
        TrackList {
            metadata_cache: RefCell::new(HashMap::with_capacity(ids.len())),
            ids,
        }
    }

    /// Get a list of [`TrackID`]s that are part of this [`TrackList`]. The order matters.
    pub fn ids(&self) -> &[TrackID] {
        self.ids.as_ref()
    }

    /// Returns the number of tracks on the list.
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    /// If the tracklist is empty or not.
    pub fn is_empty(&self) -> bool {
        self.ids.is_empty()
    }

    /// Return the [`TrackID`] of the index. Out-of-bounds will result in [`None`].
    pub fn get(&self, index: usize) -> Option<&TrackID> {
        self.ids.get(index)
    }

    /// Insert a new track (via its metadata) after another one. If the provided ID cannot be found
    /// on the list, it will be inserted at the end.
    ///
    /// **NOTE:** This is *not* something that will affect a player's actual tracklist; this is
    /// strictly for client-side representation. Use this if you want to maintain your own instance
    /// of [`TrackList`] or to feed your code with test fixtures.
    pub fn insert(&mut self, after: &TrackID, metadata: Metadata) {
        let new_id = match metadata.track_id() {
            Some(val) => val,
            // Cannot insert ID if there is no ID in the metadata.
            None => return,
        };

        let index = self.index_of_id(after).unwrap_or(self.ids.len());

        // Vec::insert inserts BEFORE the given index, but we need to insert *after* the index.
        if index >= self.ids.len() {
            self.ids.push(new_id.clone());
        } else {
            self.ids.insert(index + 1, new_id.clone());
        }

        self.change_metadata(|cache| cache.insert(new_id, metadata));
    }

    /// Removes a track from the list and metadata cache.
    ///
    /// **Note:** If the same id is present multiple times, all of them will be removed.
    pub fn remove(&mut self, id: &TrackID) {
        self.ids.retain(|existing_id| existing_id != id);

        self.change_metadata(|cache| cache.remove(id));
    }

    /// Clears the entire list and cache.
    pub fn clear(&mut self) {
        self.ids.clear();
        self.change_metadata(|cache| cache.clear());
    }

    /// Replace the contents with the contents of the provided list. Cache will be reused when
    /// possible.
    pub fn replace(&mut self, other: TrackList) {
        self.ids = other.ids;
        let other_cache = other.metadata_cache.into_inner();

        self.change_metadata(|self_cache| {
            // Will overwrite existing keys on conflicts; e.g. the newer cache wins.
            self_cache.extend(other_cache);
        });
    }

    /// Adds/updates the metadata cache for a track (as identified by [`Metadata::track_id`]).
    ///
    /// The metadata will be added to the cache even if the [`TrackID`] isn't part of the list, but
    /// will be cleaned out again after the next cache cleanup unless the track in question have
    /// been added to the list before then.
    ///
    /// If provided metadata does not contain a [`TrackID`], the metadata will be discarded.
    pub fn add_metadata(&mut self, metadata: Metadata) {
        if let Some(id) = metadata.track_id() {
            self.change_metadata(|cache| cache.insert(id.to_owned(), metadata));
        }
    }

    /// Replaces a track on the list with a new entry. The new metadata could contain a new track
    /// ID, and will in that case replace the old ID on the tracklist.
    ///
    /// The new ID (which *might* be identical to the old ID) will be returned by this method.
    ///
    /// If the old ID cannot be found, the metadata will be discarded and [`None`] will be returned.
    ///
    /// If provided metadata does not contain a [`TrackID`], the metadata will be discarded and
    /// [`None`] will be returned.
    pub fn replace_track_metadata(
        &mut self,
        old_id: &TrackID,
        new_metadata: Metadata,
    ) -> Option<TrackID> {
        if let Some(new_id) = new_metadata.track_id() {
            if let Some(index) = self.index_of_id(old_id) {
                self.ids[index] = new_id.to_owned();
                self.change_metadata(|cache| cache.insert(new_id.to_owned(), new_metadata));

                return Some(new_id);
            }
        }

        None
    }

    /// Iterates the tracks in the tracklist, returning a tuple of [`TrackID`] and [`Metadata`] for that
    /// track.
    ///
    /// [`Metadata`] will be loaded from the provided player when not present in the metadata cache.
    /// If metadata loading fails, then a [`DBusError`] will be returned instead of the iterator.
    pub fn metadata_iter(&self, player: &Player) -> Result<MetadataIter, TrackListError> {
        self.complete_cache(player)?;
        let metadata: HashMap<_, _> = self.metadata_cache.clone().into_inner();
        let ids = self.ids.clone();

        Ok(MetadataIter {
            current: 0,
            order: ids,
            metadata,
        })
    }

    /// Reloads the tracklist from the given player. This can be compared with loading a new track
    /// list, but in this case the metadata cache can be maintained for tracks that remain on the
    /// list.
    ///
    /// Cache for tracks that are no longer part of the player's tracklist will be removed.
    pub fn reload(&mut self, player: &Player) -> Result<(), TrackListError> {
        self.ids = player.get_track_list()?.ids;
        self.clear_extra_cache();
        Ok(())
    }

    /// Clears all cache and reloads metadata for all tracks.
    ///
    /// Cache will be replaced *after* the new metadata has been loaded, so on load errors the
    /// cache will still be maintained.
    pub fn reload_cache(&self, player: &Player) -> Result<(), TrackListError> {
        let id_metadata = self
            .ids
            .iter()
            .cloned()
            .zip(player.get_tracks_metadata(&self.ids)?);

        // We only have a &self reference, so fail if we cannot borrow.
        let mut cache = self.metadata_cache.try_borrow_mut()?;
        *cache = id_metadata.collect();

        Ok(())
    }

    /// Fill in any holes in the cache so that each track on the list has a cached [`Metadata`] entry.
    ///
    /// If all tracks already have a cache entry, then this will do nothing.
    pub fn complete_cache(&self, player: &Player) -> Result<(), TrackListError> {
        let ids: Vec<_> = self.ids_without_cache().into_iter().cloned().collect();
        if !ids.is_empty() {
            let metadata = player.get_tracks_metadata(&ids)?;

            // We only have a &self reference, so fail if we cannot borrow.
            let mut cache = self.metadata_cache.try_borrow_mut()?;

            for info in metadata.into_iter() {
                if let Some(id) = info.track_id() {
                    cache.insert(id, info);
                }
            }
        }
        Ok(())
    }

    /// Change metadata cache. As this requires a `&mut self`, the borrow is guaranteed to work.
    fn change_metadata<T, F>(&mut self, f: F) -> T
    where
        F: FnOnce(&mut HashMap<TrackID, Metadata>) -> T,
    {
        let mut cache = self.metadata_cache.borrow_mut(); // Safe. &mut self reference.
        f(&mut cache)
    }

    fn ids_without_cache(&self) -> Vec<&TrackID> {
        let cache = &*self.metadata_cache.borrow();
        self.ids
            .iter()
            .filter(|id| !cache.contains_key(id))
            .collect()
    }

    fn clear_extra_cache(&mut self) {
        let ids: Vec<TrackID> = self.ids().iter().map(TrackID::from).collect();

        self.change_metadata(|cache| {
            // For each id in the list, move the cache out into a new HashMap, then replace the old
            // one with the new. Only ids on the list will therefore be present on the new list.
            let new_cache: HashMap<TrackID, Metadata> = ids
                .iter()
                .flat_map(|id| cache.remove(id).map(|value| (id.to_owned(), value)))
                .collect();

            *cache = new_cache;
        });
    }

    fn index_of_id(&self, id: &TrackID) -> Option<usize> {
        self.ids
            .iter()
            .enumerate()
            .find(|(_, item_id)| *item_id == id)
            .map(|(index, _)| index)
    }
}

impl PartialEq<TrackList> for TrackList {
    fn eq(&self, other: &TrackList) -> bool {
        self.ids.eq(&other.ids)
    }
}

impl Iterator for MetadataIter {
    type Item = Metadata;

    fn next(&mut self) -> Option<Self::Item> {
        match self.order.get(self.current) {
            Some(next_id) => {
                self.current += 1;
                // In case of race conditions with cache population, emit a simple Metadata without
                // any interesting data in it.
                Some(
                    self.metadata
                        .remove(next_id)
                        .unwrap_or_else(|| Metadata::new(next_id.clone())),
                )
            }
            None => None,
        }
    }
}

impl From<::std::cell::BorrowMutError> for TrackListError {
    fn from(error: ::std::cell::BorrowMutError) -> TrackListError {
        TrackListError::BorrowError(format!("Could not borrow mutably: {}", error))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn track_id(s: &str) -> TrackID {
        TrackID::new(s).expect("Failed to parse a TrackID fixture")
    }

    mod track_list {
        use super::*;

        #[test]
        fn it_inserts_after_given_id() {
            let first = track_id("/path/1");
            let third = track_id("/path/3");

            let mut list = TrackList {
                ids: vec![first, third],
                metadata_cache: RefCell::new(HashMap::new()),
            };

            let metadata = Metadata::new("/path/new");
            list.insert(&track_id("/path/1"), metadata);

            assert_eq!(list.len(), 3);
            assert_eq!(
                &list.ids,
                &[
                    track_id("/path/1"),
                    track_id("/path/new"),
                    track_id("/path/3")
                ]
            );
            assert_eq!(
                list.ids_without_cache(),
                vec![&track_id("/path/1"), &track_id("/path/3")],
            );
        }

        #[test]
        fn it_inserts_at_end_on_missing_id() {
            let first = track_id("/path/1");
            let third = track_id("/path/3");

            let mut list = TrackList {
                ids: vec![first, third],
                metadata_cache: RefCell::new(HashMap::new()),
            };

            let metadata = Metadata::new("/path/new");
            list.insert(&track_id("/path/missing"), metadata);

            assert_eq!(list.len(), 3);
            assert_eq!(
                &list.ids,
                &[
                    track_id("/path/1"),
                    track_id("/path/3"),
                    track_id("/path/new"),
                ]
            );
            assert_eq!(
                list.ids_without_cache(),
                vec![&track_id("/path/1"), &track_id("/path/3")],
            );
        }

        #[test]
        fn it_inserts_at_end_on_empty() {
            let mut list = TrackList::default();

            let metadata = Metadata::new("/path/new");
            list.insert(&track_id("/path/missing"), metadata);

            assert_eq!(list.len(), 1);
            assert_eq!(&list.ids, &[track_id("/path/new")]);
            assert!(list.ids_without_cache().is_empty());
        }
    }
}