summaryrefslogtreecommitdiffstats
path: root/src/component.rs
blob: 3c294b309912eb93465c0222fe2de56a84267c95 (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
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
use std::{
    future::Future,
    io::{BufReader, Read},
    marker::Send,
    sync::Arc,
};

use tokio::{
    sync::{mpsc::Sender, Mutex},
    task::JoinSet,
};
use zbus::Connection;

use crate::{
    dbus::{
        player::{PlaybackStatus, PlayerProxy},
        playerctld::PlayerctldProxy,
    },
    i3bar::{Block, Click},
    Error, IGNORED,
};

pub use icon::Icon;
pub use next::Next;
pub use play::Play;
pub use prev::Prev;
pub use title::Title;
pub use volume::Volume;

mod icon;
mod next;
mod play;
mod prev;
mod title;
mod volume;

pub trait Component: Send + 'static {
    const NAME: &'static str;
    type Updater: Update;
    type Colorer: Update;
    type Handler: Button;
}

pub trait Runner: Component + private::Sealed {
    fn run<R: Read + Send>(reader: R) -> impl Future<Output = Result<(), Error>> + Send {
        async move {
            use std::io::BufRead;

            let conn = Connection::session().await?;

            let listeners = tokio::spawn(Self::listeners(conn.clone()));
            let buf_reader = BufReader::new(reader);

            for click in buf_reader
                .lines()
                .map_while(Result::ok)
                .flat_map(|s| serde_json::from_str::<Click>(&s))
            {
                let _ = <Self::Handler as Button>::handle(conn.clone(), click).await;
            }

            listeners.await?
        }
    }

    fn listeners(conn: Connection) -> impl Future<Output = Result<(), Error>> + Send {
        async move {
            use futures_util::StreamExt;

            let mut join_set = JoinSet::new();

            let (tx_player, mut rx_player) = tokio::sync::mpsc::channel(128);
            let (tx_status, mut rx_status) = tokio::sync::mpsc::channel(128);
            let (tx_value, mut rx_value) = tokio::sync::mpsc::channel(128);

            let proxy = PlayerctldProxy::builder(&conn).build().await?;

            tokio::spawn(async move {
                let mut last = proxy
                    .player_names()
                    .await?
                    .into_iter()
                    .find(|s| s.split('.').nth(3).is_some_and(|s| !IGNORED.contains(&s)))
                    .unwrap_or_default();
                tx_player.send(last.clone()).await?;
                let mut stream = proxy.receive_active_player_change_end().await?;
                while let Some(signal) = stream.next().await {
                    let name = signal.args()?.name.to_owned();
                    if name != last
                        && name
                            .split('.')
                            .nth(3)
                            .is_some_and(|s| !IGNORED.contains(&s))
                    {
                        last.clone_from(&name);
                        tx_player.send(name).await?;
                    }
                }
                Result::<_, Error>::Ok(())
            });

            let block = Arc::new(Mutex::new(Block {
                name: Some(format!("mpris-{}", Self::NAME)),
                ..Default::default()
            }));

            loop {
                let updated = tokio::select! {
                    Some(name) = rx_player.recv() => {
                        join_set.shutdown().await;

                        let mut block = block.lock().await;
                        block.full_text = String::new();
                        block.instance = None;
                        if !name.is_empty() {
                            block.instance.clone_from(&Some(name.clone()));
                            let proxy = PlayerProxy::builder(&conn)
                                .destination(name)?
                                .build()
                                .await?;
                            join_set.spawn(<Self::Colorer as Update>::listen(tx_status.clone(), proxy.clone()));
                            join_set.spawn(<Self::Updater as Update>::listen(tx_value.clone(), proxy));
                            false
                        } else {
                            true
                        }
                    }
                    Some(color) = rx_status.recv() => <Self::Colorer as Update>::update(color, block.clone()).await?,
                    Some(value) = rx_value.recv() => <Self::Updater as Update>::update(value, block.clone()).await?
                };

                if updated {
                    let s = block.lock().await;
                    s.write_stdout()?;
                }
            }
        }
    }
}

impl<T: Component> Runner for T {}

mod private {
    pub trait Sealed {}

    impl<T: super::Component> Sealed for T {}
}

pub trait Update: Send + 'static {
    type Value: Send;

    fn listen(
        tx: Sender<Self::Value>,
        proxy: PlayerProxy<'_>,
    ) -> impl Future<Output = Result<(), Error>> + Send;

    fn update(
        value: Self::Value,
        block: Arc<Mutex<Block>>,
    ) -> impl Future<Output = Result<bool, Error>> + Send;
}

impl Update for () {
    type Value = ();

    async fn listen(_: Sender<Self::Value>, _: PlayerProxy<'_>) -> Result<(), Error> {
        Ok(())
    }

    async fn update(_: Self::Value, _: Arc<Mutex<Block>>) -> Result<bool, Error> {
        Ok(false)
    }
}

impl Update for PlaybackStatus {
    type Value = (Option<String>, Option<String>);

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

        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 mut stream = proxy.receive_playback_status_changed().await;
        while let Some(signal) = stream.next().await {
            if let Ok(value) = signal.get().await {
                let val = match value {
                    PlaybackStatus::Playing => (black.clone(), cyan.clone()),
                    PlaybackStatus::Paused => (black.clone(), yellow.clone()),
                    PlaybackStatus::Stopped => (None, None),
                };
                tx.send(val).await?;
            }
        }
        Ok(())
    }

    async fn update(
        (color, background): Self::Value,
        block: Arc<Mutex<Block>>,
    ) -> Result<bool, Error> {
        let mut block = block.lock().await;
        block.color = color;
        block.background = background;
        Ok(true)
    }
}

pub trait Button {
    fn handle(
        conn: zbus::Connection,
        click: crate::i3bar::Click,
    ) -> impl Future<Output = Result<(), Error>> + Send;
}

impl Button for () {
    async fn handle(_: zbus::Connection, _: crate::i3bar::Click) -> Result<(), Error> {
        Ok(())
    }
}