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
use serde_derive::Deserialize;

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use crossbeam_channel::Sender;
use dbus::{
    arg::RefArg,
    ffidisp::stdintf::org_freedesktop_dbus::{ObjectManager, Properties},
    message::SignalArgs,
};

use crate::blocks::{Block, ConfigBlock, Update};
use crate::config::SharedConfig;
use crate::errors::*;
use crate::formatting::value::Value;
use crate::formatting::FormatTemplate;
use crate::input::{I3BarEvent, MouseButton};
use crate::scheduler::Task;
use crate::widgets::text::TextWidget;
use crate::widgets::{I3BarWidget, State};

pub struct BluetoothDevice {
    pub path: String,
    pub icon: Option<String>,
    pub label: String,
    con: dbus::ffidisp::Connection,
    available: Arc<Mutex<bool>>,
}

impl BluetoothDevice {
    pub fn new(mac: String, label: Option<String>) -> Result<Self> {
        let con = dbus::ffidisp::Connection::get_private(dbus::ffidisp::BusType::System)
            .block_error("bluetooth", "Failed to establish D-Bus connection.")?;

        // Bluez does not provide a convenient way to list devices, so we
        // have to employ a rather verbose workaround.
        let objects = con
            .with_path("org.bluez", "/", 1000)
            .get_managed_objects()
            .block_error("bluetooth", "Failed to get managed objects from org.bluez.")?;

        let devices: Vec<(dbus::Path, String)> = objects
            .into_iter()
            .filter(|(_, interfaces)| interfaces.contains_key("org.bluez.Device1"))
            .map(|(path, interfaces)| {
                let props = interfaces.get("org.bluez.Device1").unwrap();
                // This could be made safer; however this is the documented
                // D-Bus API format, so it's not a terrible idea to panic if it
                // is violated.
                let address: String = props
                    .get("Address")
                    .unwrap()
                    .0
                    .as_str()
                    .unwrap()
                    .to_string();
                (path, address)
            })
            .collect();

        // If we need to suppress errors from missing devices, this is the place
        // to do it. We could also pick the "default" device here, although that
        // does not make much sense to me in the context of Bluetooth.
        let mut initial_available = false;
        let auto_path = devices
            .into_iter()
            .filter(|(_, address)| address == &mac)
            .map(|(path, _)| path)
            .next();
        let path = if let Some(p) = auto_path {
            initial_available = true;
            p
        } else {
            // TODO: do not hardcode device
            dbus::strings::Path::new(format!("/org/bluez/hci0/dev_{}", mac.replace(":", "_")))
                .unwrap()
        }
        .to_string();

        // Swallow errors, since this is optional.
        let icon: Option<String> = con
            .with_path("org.bluez", &path, 1000)
            .get("org.bluez.Device1", "Icon")
            .ok();

        // TODO: revisit this lint
        #[allow(clippy::mutex_atomic)]
        let available = Arc::new(Mutex::new(initial_available));

        Ok(BluetoothDevice {
            path,
            icon,
            label: label.unwrap_or_else(|| "".to_string()),
            con,
            available,
        })
    }

    pub fn battery(&self) -> Option<u8> {
        // Swallow errors here; not all devices implement this API.
        self.con
            .with_path("org.bluez", &self.path, 1000)
            .get("org.bluez.Battery1", "Percentage")
            .ok()
    }

    pub fn icon(&self) -> Option<String> {
        self.con
            .with_path("org.bluez", &self.path, 1000)
            .get("org.bluez.Device1", "Icon")
            .ok()
    }

    pub fn available(&self) -> Result<bool> {
        Ok(*self
            .available
            .lock()
            .block_error("bluetooth", "failed to acquire lock for `available`")?)
    }

    pub fn connected(&self) -> bool {
        self.con
            .with_path("org.bluez", &self.path, 1000)
            .get("org.bluez.Device1", "Connected")
            // In the case that the D-Bus interface missing or responds
            // incorrectly, it seems reasonable to treat the device as "down"
            // instead of nuking the bar. This matches the behaviour elsewhere.
            .unwrap_or(false)
    }

    pub fn toggle(&self) -> Result<()> {
        // TODO: power on adapter if it's off
        // i.e. busctl --system set-property org.bluez /org/bluez/hci0 org.bluez.Adapter1 Powered b true
        let method = if self.connected() {
            "Disconnect"
        } else {
            "Connect"
        };
        let msg =
            dbus::Message::new_method_call("org.bluez", &self.path, "org.bluez.Device1", method)
                .block_error("bluetooth", "Failed to build D-Bus method.")?;

        // Swallow errors rather than nuke the bar.
        let _ = self.con.send(msg);
        Ok(())
    }

    /// Monitor Bluetooth property changes in a separate thread and send updates
    /// via the `update_request` channel.
    pub fn monitor(&self, id: usize, update_request: Sender<Task>) {
        let path_copy1 = self.path.clone();
        let path_copy2 = self.path.clone();
        let avail_copy1 = self.available.clone();
        let avail_copy2 = self.available.clone();
        let update_request_copy1 = update_request.clone();
        let update_request_copy2 = update_request.clone();
        let update_request_copy3 = update_request;

        thread::Builder::new().name("bluetooth".into()).spawn(move || {
            let c = dbus::blocking::Connection::new_system().unwrap();
            use dbus::ffidisp::stdintf::org_freedesktop_dbus::ObjectManagerInterfacesAdded as IA;
            let ma = IA::match_rule(Some(&"org.bluez".into()), None).static_clone();
            c.add_match(ma, move |ia: IA, _, _| {
                if ia.object == path_copy1.clone().into() {
                    let mut avail = avail_copy1.lock().unwrap();
                    *avail = true;
                    update_request_copy1
                        .send(Task {
                            id,
                            update_time: Instant::now(),
                        })
                        .unwrap();
                }
                true
            })
            .unwrap();

            use dbus::ffidisp::stdintf::org_freedesktop_dbus::ObjectManagerInterfacesRemoved as IR;
            let mr = IR::match_rule(Some(&"org.bluez".into()), None).static_clone();
            c.add_match(mr, move |ir: IR, _, _| {
                if ir.object == path_copy2.clone().into() {
                    let mut avail = avail_copy2.lock().unwrap();
                    *avail = false;
                    update_request_copy2
                        .send(Task {
                            id,
                            update_time: Instant::now(),
                        })
                        .unwrap();
                }
                true
            })
            .unwrap();

            use dbus::ffidisp::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged as PPC;
            let mr = PPC::match_rule(Some(&"org.bluez".into()), None).static_clone();
            // TODO: get updated values from the signal message
            c.add_match(mr, move |_ppc: PPC, _, _| {
                update_request_copy3
                    .send(Task {
                        id,
                        update_time: Instant::now(),
                    })
                    .unwrap();
                true
            })
            .unwrap();

            loop {
                c.process(Duration::from_millis(1000)).unwrap();
            }
        }).unwrap();
    }
}

pub struct Bluetooth {
    id: usize,
    output: TextWidget,
    device: BluetoothDevice,
    hide_disconnected: bool,
    format: FormatTemplate,
    format_unavailable: FormatTemplate,
}

#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct BluetoothConfig {
    pub mac: String,
    //DEPRECATED
    //TODO remove
    pub label: Option<String>,
    #[serde(default = "BluetoothConfig::default_hide_disconnected")]
    pub hide_disconnected: bool,
    #[serde(default = "BluetoothConfig::default_format")]
    pub format: String,
    #[serde(default = "BluetoothConfig::default_format_unavailable")]
    pub format_unavailable: String,
}

impl BluetoothConfig {
    fn default_hide_disconnected() -> bool {
        false
    }

    fn default_format() -> String {
        "{label} {percentage}".into()
    }

    fn default_format_unavailable() -> String {
        "{label} x".into()
    }
}

impl ConfigBlock for Bluetooth {
    type Config = BluetoothConfig;

    fn new(
        id: usize,
        block_config: Self::Config,
        shared_config: SharedConfig,
        send: Sender<Task>,
    ) -> Result<Self> {
        let device = BluetoothDevice::new(block_config.mac, block_config.label)?;
        device.monitor(id, send);

        Ok(Bluetooth {
            id,
            output: TextWidget::new(id, 0, shared_config).with_icon(match device.icon {
                Some(ref icon) if icon == "audio-card" => "headphones",
                Some(ref icon) if icon == "input-gaming" => "joystick",
                Some(ref icon) if icon == "input-keyboard" => "keyboard",
                Some(ref icon) if icon == "input-mouse" => "mouse",
                _ => "bluetooth",
            })?,
            device,
            hide_disconnected: block_config.hide_disconnected,
            format: FormatTemplate::from_string(&block_config.format)?,
            format_unavailable: FormatTemplate::from_string(&block_config.format_unavailable)?,
        })
    }
}

impl Block for Bluetooth {
    fn id(&self) -> usize {
        self.id
    }

    fn update(&mut self) -> Result<Option<Update>> {
        if self.device.available()? {
            let values = map!(
                "{label}" => Value::from_string(self.device.label.clone()),
                "{percentage}" => Value::from_integer(self.device.battery().unwrap_or(0) as i64).percents(),
            );
            let connected = self.device.connected();
            self.output.set_text(self.device.label.to_string());
            self.output
                .set_state(if connected { State::Good } else { State::Idle });

            self.output.set_icon(match self.device.icon() {
                Some(ref icon) if icon == "audio-card" => "headphones",
                Some(ref icon) if icon == "input-gaming" => "joystick",
                Some(ref icon) if icon == "input-keyboard" => "keyboard",
                Some(ref icon) if icon == "input-mouse" => "mouse",
                _ => "bluetooth",
            })?;

            // Use battery info, when available.
            if let Some(value) = self.device.battery() {
                self.output.set_state(match value {
                    0..=15 => State::Critical,
                    16..=30 => State::Warning,
                    31..=60 => State::Info,
                    61..=100 => State::Good,
                    _ => State::Warning,
                });
            }
            self.output.set_text(self.format.render(&values)?);
        } else {
            let values = map!(
                "{label}" => Value::from_string(self.device.label.clone()),
                "{percentage}" => Value::from_string("".into()),
            );
            self.output.set_state(State::Idle);
            self.output
                .set_text(self.format_unavailable.render(&values)?);
        }

        Ok(None)
    }

    fn click(&mut self, event: &I3BarEvent) -> Result<()> {
        if let MouseButton::Right = event.button {
            self.device.toggle()?;
        }
        Ok(())
    }

    fn view(&self) -> Vec<&dyn I3BarWidget> {
        if !self.device.connected() && self.hide_disconnected {
            vec![]
        } else {
            vec![&self.output]
        }
    }
}