crabshell-services 0.2.0

Crabshell's services: workspaces, tray, audio, clock, power, Bluetooth, network, media players, notifications, apps, programs, files, PAM, greetd and polkit
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
516
517
518
519
520
521
522
523
524
525
//! Bluetooth adapters and devices from BlueZ, on the system bus.

#[cfg(test)]
mod tests;

use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use std::sync::Once;

use crabshell_reactive::{ReadSignal, Signal};
use crabshell_ui::Cx;
use zbus::{Connection, Message, ObjectPath, OwnedObjectPath, Variant};

use crate::Shared;
use crate::dbus::{self, CALL_TIMEOUT, Daemon, OBJECT_MANAGER, PROPERTIES, Props, set_changed};

const BLUEZ: &str = "org.bluez";
const ADAPTER: &str = "org.bluez.Adapter1";
const DEVICE: &str = "org.bluez.Device1";
const BATTERY: &str = "org.bluez.Battery1";

/// The most adapters shown: one per radio.
const MAX_ADAPTERS: usize = 16;
/// The most devices shown: discovery adds every device in range.
const MAX_DEVICES: usize = 256;
/// The most objects kept, so a flood can't take the memory.
const MAX_OBJECTS: usize = 4096;
/// How long `Pair` and `Connect` may take: BlueZ answers a pairing only
/// once the user confirmed it in the agent's prompt.
const SLOW_CALL: std::time::Duration = std::time::Duration::from_secs(90);

/// The properties this service reads, by interface: a change to any
/// other, such as a device's signal strength during discovery, shows
/// nothing new.
fn read(interface: &str, name: &str) -> bool {
  match interface {
    ADAPTER => matches!(name, "Alias" | "Address" | "Powered" | "Discovering"),
    DEVICE => matches!(
      name,
      "Address" | "Alias" | "Name" | "Icon" | "Connected" | "Paired" | "Trusted" | "Adapter"
    ),
    BATTERY => name == "Percentage",
    _ => false,
  }
}

/// A Bluetooth radio BlueZ knows.
#[derive(Clone, Debug, PartialEq)]
pub struct BluetoothAdapter {
  /// BlueZ's object path for it, such as `/org/bluez/hci0`.
  pub path: String,
  /// Its name, BlueZ's `Alias`.
  pub name: String,
  /// Its address, such as `00:1A:7D:DA:71:13`.
  pub address: String,
  /// Whether it is on.
  pub powered: bool,
  /// Whether it is looking for devices.
  pub discovering: bool,
}

impl BluetoothAdapter {
  fn from_props(path: String, props: &Props) -> BluetoothAdapter {
    BluetoothAdapter {
      path,
      name: dbus::text(props, "Alias"),
      address: dbus::text(props, "Address"),
      powered: dbus::get(props, "Powered").unwrap_or(false),
      discovering: dbus::get(props, "Discovering").unwrap_or(false),
    }
  }
}

/// A device BlueZ knows: one paired before, or one discovery found.
#[derive(Clone, Debug, PartialEq)]
pub struct BluetoothDevice {
  /// BlueZ's object path for it, which names it while it exists.
  pub path: String,
  /// The path of the adapter it is reached through.
  pub adapter: String,
  /// Its address, such as `AA:BB:CC:DD:EE:01`.
  pub address: String,
  /// Its `Alias`, else its `Name`, else its address.
  pub name: String,
  /// The icon BlueZ suggests, such as `audio-headset`, or `""`.
  pub icon: String,
  /// Whether it is connected.
  pub connected: bool,
  /// Whether it is paired.
  pub paired: bool,
  /// Whether it may connect without asking.
  pub trusted: bool,
  /// How full its battery is, from 0 to 100, if it says.
  pub battery: Option<u8>,
}

impl BluetoothDevice {
  fn from_props(path: String, props: &Props, battery: Option<&Props>) -> BluetoothDevice {
    let address = dbus::text(props, "Address");
    let name = [dbus::text(props, "Alias"), dbus::text(props, "Name")]
      .into_iter()
      .find(|name| !name.is_empty())
      .unwrap_or_else(|| address.clone());
    BluetoothDevice {
      path,
      adapter: dbus::get::<&ObjectPath>(props, "Adapter")
        .map_or(String::new(), |at| at.to_string()),
      address,
      name,
      icon: dbus::text(props, "Icon"),
      connected: dbus::get(props, "Connected").unwrap_or(false),
      paired: dbus::get(props, "Paired").unwrap_or(false),
      trusted: dbus::get(props, "Trusted").unwrap_or(false),
      battery: battery
        .and_then(|props| dbus::get::<u8>(props, "Percentage"))
        .map(|percent| percent.min(100)),
    }
  }
}

/// Bluetooth from BlueZ, from `cx.bluetooth()`. Cloning it is cheap.
#[derive(Clone)]
pub struct Bluetooth {
  service: Option<Rc<BluetoothService>>,
  adapters: ReadSignal<Vec<BluetoothAdapter>>,
  devices: ReadSignal<Vec<BluetoothDevice>>,
}

impl Bluetooth {
  /// Every adapter, in path order. Empty while BlueZ isn't running.
  pub fn adapters(&self) -> ReadSignal<Vec<BluetoothAdapter>> {
    self.adapters
  }

  /// Every device BlueZ knows, in path order. Empty while BlueZ isn't
  /// running.
  pub fn devices(&self) -> ReadSignal<Vec<BluetoothDevice>> {
    self.devices
  }

  /// Turns the adapter at `adapter`, its path, on or off.
  pub fn set_powered(&self, adapter: &str, powered: bool) {
    let body = (ADAPTER, "Powered", Variant::from(powered));
    self.call(adapter, PROPERTIES, "Set", body);
  }

  /// Starts looking for devices. Found ones join [`devices`] until BlueZ
  /// forgets them, a while after [`stop_discovery`].
  ///
  /// [`devices`]: Self::devices
  /// [`stop_discovery`]: Self::stop_discovery
  pub fn start_discovery(&self, adapter: &str) {
    self.call(adapter, ADAPTER, "StartDiscovery", ());
  }

  /// Stops looking for devices.
  pub fn stop_discovery(&self, adapter: &str) {
    self.call(adapter, ADAPTER, "StopDiscovery", ());
  }

  /// Connects the device at `device`, its path.
  pub fn connect(&self, device: &str) {
    self.call(device, DEVICE, "Connect", ());
  }

  /// Disconnects the device at `device`.
  pub fn disconnect(&self, device: &str) {
    self.call(device, DEVICE, "Disconnect", ());
  }

  /// Pairs with the device at `device`. The shell answers no pairing
  /// questions, so a device that asks for a PIN or a confirmation fails,
  /// and that is logged, unless another program on the desktop answers
  /// for BlueZ.
  pub fn pair(&self, device: &str) {
    self.call(device, DEVICE, "Pair", ());
  }

  /// Lets the device at `device` connect without asking, or not.
  pub fn set_trusted(&self, device: &str, trusted: bool) {
    let body = (DEVICE, "Trusted", Variant::from(trusted));
    self.call(device, PROPERTIES, "Set", body);
  }

  /// Unpairs the device at `device` and has its adapter forget it.
  pub fn forget(&self, device: &str) {
    let adapter = self.service.as_ref().and_then(|service| {
      let state = service.state.borrow();
      let object = state.as_ref()?.objects.get(device)?;
      dbus::get::<&ObjectPath>(object.device.as_ref()?, "Adapter").map(|at| at.to_string())
    });
    let (Some(adapter), Ok(path)) = (adapter, ObjectPath::try_from(device.to_owned())) else {
      return tracing::info!(device, "no such Bluetooth device; nothing forgotten");
    };
    self.call(&adapter, ADAPTER, "RemoveDevice", path);
  }

  /// Calls `method` on BlueZ's object at `path`, and logs a refusal.
  fn call<B>(&self, path: &str, interface: &'static str, method: &'static str, body: B)
  where
    B: serde::Serialize + zbus::DynamicType + 'static,
  {
    let Some(service) = &self.service else {
      return;
    };
    let Some(connection) = service
      .state
      .borrow()
      .as_ref()
      .and_then(|state| state.connection.clone())
    else {
      return tracing::info!(method, "BlueZ isn't running; nothing sent");
    };
    let (shared, path) = (Rc::clone(&service.shared), path.to_owned());
    service.shared.spawn(async move {
      let call = connection.call_method(Some(BLUEZ), path.as_str(), Some(interface), method, &body);
      let limit = if matches!(method, "Pair" | "Connect") {
        SLOW_CALL
      } else {
        CALL_TIMEOUT
      };
      if let Err(error) = shared.timeout(limit, call).await {
        tracing::warn!(%error, path, method, "BlueZ refused it");
      }
    });
  }
}

/// `cx.bluetooth()`.
pub(crate) fn bluetooth(cx: &Cx) -> Bluetooth {
  let Some(service) = cx.service::<BluetoothService>() else {
    static LOGGED: Once = Once::new();
    LOGGED.call_once(|| {
      tracing::warn!("cx.bluetooth() needs the services the shell provides; it stays empty");
    });
    return Bluetooth {
      service: None,
      adapters: cx.signal(Vec::new()).read_only(),
      devices: cx.signal(Vec::new()).read_only(),
    };
  };
  service.start()
}

/// BlueZ for one shell, followed from the first ask.
pub(crate) struct BluetoothService {
  shared: Rc<Shared>,
  state: RefCell<Option<BluetoothState>>,
}

struct BluetoothState {
  adapters: Signal<Vec<BluetoothAdapter>>,
  devices: Signal<Vec<BluetoothDevice>>,
  /// BlueZ's adapters and devices, by path.
  objects: BTreeMap<String, Object>,
  /// The bus, while BlueZ runs, for the methods.
  connection: Option<Connection>,
  generation: u64,
}

/// The interfaces this service reads on one of BlueZ's objects. An
/// object is kept while it is an adapter or a device.
#[derive(Default)]
struct Object {
  adapter: Option<Props>,
  device: Option<Props>,
  battery: Option<Props>,
}

impl Object {
  /// Where `interface`'s properties go, or `None` for one this service
  /// doesn't read.
  fn slot(&mut self, interface: &str) -> Option<&mut Option<Props>> {
    match interface {
      ADAPTER => Some(&mut self.adapter),
      DEVICE => Some(&mut self.device),
      BATTERY => Some(&mut self.battery),
      _ => None,
    }
  }
}

/// Gives the object at `path` `interfaces`. Past [`MAX_OBJECTS`] a new
/// one is left out; which are shown is decided as they are.
fn add(objects: &mut BTreeMap<String, Object>, path: String, interfaces: HashMap<String, Props>) {
  if objects.len() >= MAX_OBJECTS && !objects.contains_key(&path) {
    return tracing::debug!(path, "too many Bluetooth objects; leaving one out");
  }
  let mut object = objects.remove(&path).unwrap_or_default();
  for (interface, props) in interfaces {
    if let Some(slot) = object.slot(&interface) {
      *slot = Some(props);
    }
  }
  if object.adapter.is_some() || object.device.is_some() {
    objects.insert(path, object);
  }
}

impl BluetoothService {
  pub(crate) fn new(shared: Rc<Shared>) -> BluetoothService {
    BluetoothService {
      shared,
      state: RefCell::new(None),
    }
  }

  fn start(self: &Rc<Self>) -> Bluetooth {
    if let Some(state) = &*self.state.borrow() {
      return Bluetooth {
        service: Some(Rc::clone(self)),
        adapters: state.adapters.read_only(),
        devices: state.devices.read_only(),
      };
    }
    let root = &self.shared.root;
    let (adapters, devices) = (root.signal(Vec::new()), root.signal(Vec::new()));
    *self.state.borrow_mut() = Some(BluetoothState {
      adapters,
      devices,
      objects: BTreeMap::new(),
      connection: None,
      generation: 0,
    });
    match self.shared.config.system_bus.clone() {
      Some(address) => {
        let follow = dbus::follow(Rc::clone(&self.shared), Rc::clone(self), address);
        self.shared.spawn(follow);
      }
      None => tracing::info!("no system bus, so there is no Bluetooth"),
    }
    Bluetooth {
      service: Some(Rc::clone(self)),
      adapters: adapters.read_only(),
      devices: devices.read_only(),
    }
  }

  /// Shows the adapters and devices as they are now.
  fn publish(&self) {
    // Set apart from the borrow, since effects may ask for more.
    let shown = self.state.borrow().as_ref().map(|state| {
      let objects = || {
        state
          .objects
          .iter()
          .map(|(path, object)| (path.clone(), object))
      };
      let adapters = objects()
        .filter_map(|(path, object)| {
          Some(BluetoothAdapter::from_props(path, object.adapter.as_ref()?))
        })
        .take(MAX_ADAPTERS)
        .collect::<Vec<_>>();
      let mut devices = objects()
        .filter_map(|(path, object)| {
          let device = object.device.as_ref()?;
          Some(BluetoothDevice::from_props(
            path,
            device,
            object.battery.as_ref(),
          ))
        })
        .collect::<Vec<_>>();
      // Past the cap, connected and paired ones first, so the devices a
      // person uses never hide behind strangers discovery found.
      if devices.len() > MAX_DEVICES {
        devices.sort_by_key(|device| (!device.connected, !device.paired));
        devices.truncate(MAX_DEVICES);
        devices.sort_by(|a, b| a.path.cmp(&b.path));
      }
      (state.adapters, adapters, state.devices, devices)
    });
    if let Some((adapters_signal, adapters, devices_signal, devices)) = shown {
      set_changed(adapters_signal, adapters);
      set_changed(devices_signal, devices);
    }
  }
}

impl Daemon for BluetoothService {
  const NAME: &'static str = BLUEZ;

  /// Only what adapters and devices are: BlueZ also broadcasts media,
  /// GATT values and other programs' notifications, which would each
  /// wake the shell for nothing.
  fn rules() -> Vec<String> {
    let mut rules = vec![format!(
      "type='signal',sender='{BLUEZ}',interface='{OBJECT_MANAGER}'"
    )];
    rules.extend([ADAPTER, DEVICE, BATTERY].map(|interface| {
      format!(
        "type='signal',sender='{BLUEZ}',interface='{PROPERTIES}',member='PropertiesChanged',\
         arg0='{interface}'"
      )
    }));
    rules
  }

  fn alive(&self) -> bool {
    let state = self.state.borrow();
    state
      .as_ref()
      .is_some_and(|state| state.adapters.try_with(|_| ()).is_some())
  }

  fn clear(&self) -> u64 {
    let generation = {
      let mut state = self.state.borrow_mut();
      let Some(state) = state.as_mut() else {
        return 0;
      };
      state.objects.clear();
      state.connection = None;
      state.generation += 1;
      state.generation
    };
    self.publish();
    generation
  }

  async fn read(self: Rc<Self>, connection: Connection, generation: u64) {
    let call = connection.call_method(
      Some(BLUEZ),
      "/",
      Some(OBJECT_MANAGER),
      "GetManagedObjects",
      &(),
    );
    let read = async {
      let reply = self.shared.timeout(CALL_TIMEOUT, call).await?;
      reply
        .body()
        .deserialize::<HashMap<OwnedObjectPath, HashMap<String, Props>>>()
    };
    let managed = match read.await {
      Ok(managed) => managed,
      Err(error) => return tracing::warn!(%error, "couldn't read BlueZ"),
    };
    // In path order, so the caps keep the same objects every time.
    let managed = managed
      .into_iter()
      .map(|(path, interfaces)| (path.as_str().to_owned(), interfaces))
      .collect::<BTreeMap<_, _>>();
    {
      let mut state = self.state.borrow_mut();
      let Some(state) = state
        .as_mut()
        .filter(|state| state.generation == generation)
      else {
        return;
      };
      state.objects.clear();
      for (path, interfaces) in managed {
        add(&mut state.objects, path, interfaces);
      }
      state.connection = Some(connection);
    }
    self.publish();
  }

  fn signal(self: &Rc<Self>, _: &Connection, message: &Message) {
    if let Some((path, interface, changed, dropped)) = dbus::properties_changed(message) {
      {
        let mut state = self.state.borrow_mut();
        let props = state
          .as_mut()
          .and_then(|state| state.objects.get_mut(&path))
          .and_then(|object| object.slot(&interface)?.as_mut());
        let Some(props) = props else {
          return;
        };
        let shown = changed
          .keys()
          .chain(&dropped)
          .any(|name| read(&interface, name));
        dbus::apply(props, changed, dropped);
        if !shown {
          return;
        }
      }
      return self.publish();
    }
    let header = message.header();
    if header.interface().map(|interface| interface.as_str()) != Some(OBJECT_MANAGER) {
      return;
    }
    let body = message.body();
    {
      let mut state = self.state.borrow_mut();
      let Some(state) = state.as_mut() else {
        return;
      };
      match header.member().map(|member| member.as_str()) {
        Some("InterfacesAdded") => {
          let Ok((path, interfaces)) =
            body.deserialize::<(OwnedObjectPath, HashMap<String, Props>)>()
          else {
            return;
          };
          add(&mut state.objects, path.as_str().to_owned(), interfaces);
        }
        Some("InterfacesRemoved") => {
          let Ok((path, interfaces)) = body.deserialize::<(OwnedObjectPath, Vec<String>)>() else {
            return;
          };
          let Some(object) = state.objects.get_mut(path.as_str()) else {
            return;
          };
          for interface in interfaces {
            if let Some(slot) = object.slot(&interface) {
              *slot = None;
            }
          }
          if object.adapter.is_none() && object.device.is_none() {
            state.objects.remove(path.as_str());
          }
        }
        _ => return,
      }
    }
    self.publish();
  }
}