summaryrefslogtreecommitdiffstats
path: root/src/bin/mpris-play.rs
blob: 047788754329b541236c4b371596e3d23ff37611 (plain)
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
use std::sync::Arc;

use i3blocks::{
    dbus::player::{PlaybackStatus, PlayerProxy},
    i3bar::{Block, Click},
    Button, Component, Error, Update,
};
use tokio::sync::{mpsc::Sender, Mutex};
use zbus::Connection;

#[tokio::main]
async fn main() -> Result<(), main_error::MainError> {
    i3blocks::run::<Play>(Default::default())
        .await
        .map_err(Into::into)
}

pub struct Play;

impl Component for Play {
    const NAME: &'static str = "play";
    type Updater = Self;
    type Colorer = ();
    type Handler = Self;
}

impl Update for Play {
    type Value = PlaybackStatus;

    async fn listen(tx: Sender<Self::Value>, proxy: PlayerProxy<'_>) -> Result<(), Error> {
        use futures_util::StreamExt;

        tx.send(proxy.playback_status().await?).await?;
        let mut stream = proxy.receive_playback_status_changed().await;
        while let Some(signal) = stream.next().await {
            if let Ok(value) = signal.get().await {
                tx.send(value).await?;
            }
        }
        Ok(())
    }

    async fn update(value: Self::Value, block: Arc<Mutex<Block>>) -> Result<bool, Error> {
        let black = std::env::var("BASE16_COLOR_00_HEX").ok();
        let cyan = std::env::var("BASE16_COLOR_0C_HEX").ok();
        let yellow = std::env::var("BASE16_COLOR_0A_HEX").ok();

        let (full_text, color, background) = match value {
            PlaybackStatus::Playing => (" 󰏤 ", black.clone(), cyan.clone()),
            PlaybackStatus::Paused => (" 󰐊 ", black.clone(), yellow.clone()),
            PlaybackStatus::Stopped => (" 󰐊 ", None, None),
        };

        let mut block = block.lock().await;
        block.full_text = full_text.into();
        block.color = color;
        block.background = background;
        Ok(true)
    }
}

impl Button for Play {
    async fn handle(conn: Connection, click: Click) -> Result<(), Error> {
        let Some(name) = click.instance else {
            return Ok(());
        };

        if click.button == 1 {
            PlayerProxy::builder(&conn)
                .destination(name)?
                .build()
                .await?
                .play_pause()
                .await?
        }

        Ok(())
    }
}